`
heirenhua
  • 浏览: 11144 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
社区版块
存档分类
最新评论

JDBC连接MySQL的过程小结

    博客分类:
  • JDBC
阅读更多

一、准备工作

1.下载并安装MySQL以及MySQL的基本操作 

 

2.下载并安装Connector/J 

 

二、JDBC编程步骤

代码示例:

import java.sql.*;

public class TestJDBC {

	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			//1.Load the Driver,自动实例化,自动向DriverManager注册,不需显示调用DriverManager.registerDriver()方法
			Class.forName("com.mysql.jdbc.Driver");
			
			//2.Connect to the DataBase
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc", "root", "1234567");
			
			//3.Execute the SQL
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select * from student");
			
			while (rs.next()) {	//4.Retrieve the result data
				
				//5.将数据库中的各种类型转换为Java中的类型(getXXX)方法
				System.out.println(rs.getString("name"));
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			
				try {	//6.Close
					if (rs != null) {
						rs.close();
						rs = null;
					}
					if (stmt != null) {
						stmt.close();
						stmt = null;
					}
					if (conn != null) {
						conn.close();
						conn = null;
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
		
		}

	}

}

 

说明:

在MySQL中建立了一个名为“testjdbc"的Database,然后在testjdbc中建立一个名为”student“的table,MySQL中root的密码为”1234567“。

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics