经典,使用JDBC连接数据库,共五个步骤(曾经作为进入公司的面试题):
一. 加载JDBC驱动程序
二. 创建数据库连接
三. 创建一个Statement对象
四. 执行Sql语句,处理结果
五. 关闭JDBC对象,关闭连接
一. 加载JDBC驱动程序
连接数据库之前,首先要加载数据库的驱动程序类到jvm,使用java.lang.Class.forName实现。实例
try{ //加载MySql的驱动类 Class.forName("com.mysql.jdbc.Driver") ; }catch(ClassNotFoundException e){ System.out.println("找不到驱动程序类 ,加载驱动失败!"); e.printStackTrace() ; }
加载成功以后,驱动类会注册到DriverManager类中。
二. 创建数据库连接
你需要准备几个数据:连接数据库的url,用户名,密码。
使用java.sql.DriverManager类获取数据连接Connection对象,该实例表示一个数据库连接。实例
//连接MySql数据库,用户名和密码都是root String url = "jdbc:mysql://localhost:3306/test" ; String username = "root" ; String password = "root" ; try{ Connection con = DriverManager.getConnection(url , username , password ) ; }catch(SQLException se){ System.out.println("数据库连接失败!"); se.printStackTrace() ; }
三. 创建一个Statement对象
要执行一个sql语句,必须从连接中获取一个Statement对象,Statement对象有三种类型:
1. 执行静态SQL语句。通常通过Statement实例实现。
Statement stmt = connection.createStatement() ;
2. 执行动态SQL语句。通常通过PreparedStatement实例实现。 预编译语句,减少重复的sql语句编译过程,提高执行效率。
PrepareStatment ps = connection.prepareStatment("insert into 学生成绩 values (?, ?, ?)"); ps.setInt(1, 123); ps.setString(2, "Jim"); ps.setInt(3, 60); ps.executeUpdate();
3. 执行数据库存储过程。通常通过CallableStatement实例实现。
四. 执行Sql语句,处理结果
1. 执行静态的SQL语句,示例:
Statement stmt = connection.createStatment(); stmt.executeUpdate("insert into 学科代码 values (123, '计算机')"); stmt. close(); connection.close();
2. 执行动态的SQL语句,示例:
PrepareStatment ps = connection.prepareStatment("insert into 学生成绩 values (?, ?, ?)"); ps.setInt(1, 123); ps.setString(2, "Jim"); ps.setInt(3, 60); ps.executeUpdate(); ps.close(); connection.close();
五. 关闭JDBC对象,关闭连接
千万注意要关闭,一般放在finally模块中,否则会造成内存泄露、数据库连接耗尽、机器LOAD飙升等非常棘手的问题。
ps.close(); connection.close();