JDBC编程步骤:
1.Load the Driver 加载驱动(注册驱动)
(1) Class.forName("com.mysql.jdbc.Driver");|Class.forName().newInstance()|new DriverName();
//new DriverName()这种连接方式即是 new com.mysql.jdbc.Driver();
(2) 实例化时自动向DriverManager注册,不需要显式调用DriverManager.registerDriver方法
2.Connect to Database
(1) DriverManager.getConnection()
3.Execute the SQL
(1) Connection.CreateStatement()
(2) Statement.executeQuery()
(3) Statement.executeUpdate()
4.Retireve the result data
(1) 循环取得结果while(rs.next())
5.Show the result data
(1) 将数据中的各种数据类型转换为java中的类型(getXXX)方法
6.close
1.close the resultset / close the statement / close the connection
Demo
- /**
- * 代码为入门示例,主要为熟悉JDBC编程的基本流程,不在页面上显示数据,异常等不做详细考虑。
- */
- import java.sql.*;
- public class TestJDBC {
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception
- {
- // 1.Load the Driver 加载驱动(注册驱动)
- new com.mysql.jdbc.Driver();
- //或者使用这种连接方式//Class.forName("com.mysql.jdbc.Driver");
- //2.Connect to Database 连接数据库.以mysql5.0为例子,数据库名为college,用户名为root,密码是123456
- Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "123456");
- //3.Execute the SQL
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery("select * from user");
- while(rs.next()) //4.Retireve the result data 遍历结果集
- {
- //5.Show the result data 显示结果.将数据中的各种数据类型转换为java中的类型(getXXX)方法
- System.out.println("The first colum:");
- System.out.println(rs.getString("userName"));
- System.out.println("The second colum:");
- System.out.println(rs.getString("userFlag"));
- }
- //6.close 关闭连接,从后打开的开始,逆序进行关闭
- rs.close();
- stmt.close();
- conn.close();
- }
- }
再把Demo完善一点,如下:
- import java.sql.*;
- public class TestJDBC
- {
- /**
- * @param args
- */
- public static void main(String[] args)
- {
- Connection conn = null;
- Statement stmt = null;
- ResultSet rs = null;
- try
- {
- // 1.Load the Driver 加载驱动(注册驱动)
- Class.forName("com.mysql.jdbc.Driver");
- // 或者使用这种连接方式//new com.mysql.jdbc.Driver();
- // 2.Connect to Database
- // 连接数据库.以mysql5.0为例子,数据库名为college,用户名为root,密码是123456
- conn = DriverManager.getConnection(
- "jdbc:mysql://localhost:3306/college", "root", "123456");
- // 3.Execute the SQL
- stmt = conn.createStatement();
- rs = stmt.executeQuery("select * from user");
- while (rs.next()) // 4.Retireve the result data 遍历结果集
- {
- // 5.Show the result data 显示结果.将数据中的各种数据类型转换为java中的类型(getXXX)方法
- System.out.println("The first colum:");
- System.out.println(rs.getString("userName"));
- System.out.println("The second colum:");
- System.out.println(rs.getString("userFlag"));
- }
- } catch (ClassNotFoundException e)
- {
- e.printStackTrace();
- } catch (SQLException e)
- {
- e.printStackTrace();
- } finally
- {
- // 6.close 关闭连接,从后打开的开始,逆序进行关闭
- try
- {
- if (rs != null)
- {
- rs.close();
- rs = null;
- }
- if (stmt != null)
- {
- stmt.close();
- stmt = null;
- }
- if (conn != null)
- {
- conn.close();
- conn = null;
- }
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }
- }