JDBC编程六步:
- 第一步:注册驱动(作用:告诉Java程序,即将要连接的是哪个品牌的数据库, 至于驱动是什么,通俗讲就是各类数据库厂家(mysql、Oracle等)编写的JDBC接口的实现类)
- 第二步:获取连接(表示JVM的进程和数据库进程之间的通道打开了,这属于进程之间的通信,重量级的,使用完之后一定要关闭通道。)
- 第三步:获取数据库操作对象(专门执行sql语句的对象)
- 第四步:执行SQL语句(DQL DML…)
- 第五步:处理查询结果集(只有当第四步执行的是select语句的时候,才有这第五步处理查询结果集。第二段代码中有详细举例)
- 第六步:释放资源(使用完资源之后一定要关闭资源。Java和数据库属于进程间的通信,开启之后一定要关闭。)
直接看代码,后文分步详讲注册驱动的多种方法和如何处理查询集。
import java.sql.*;
public class JDBCTest{
public static void main(String[] args) {
Statement stmt = null; //获取数据库操作对象
Connection conn = null; //用于连接驱动
try {
// 第一步:注册驱动
String driver = "com.mysql.jbdc.properties.Driver"; //连接的那个数据库管理系统:此处为mysql
Class.forName(driver);
String url = "jbdc.properties:mysql://127.0.0.1:3306/databaseName";
//url : 统一资源定位符(网络中某个资源得绝对路径) 包括:协议、TP、PORT、资源名.
//例如此处url:jdbc.properties:mysql:// 协议 27.0.0.1 IP地址 3306 数据库端口号 databaseName 数据库实例名
//再例如:http://182.61.200.7:80/index.html http:// 通信协议 182.61.200.7:80 服务器IP地址 index.html 服务器某个资源名
String user = "root"; //用户
String password = "*******" ; //用户密码
// 第二步:连接驱动: 建立驱动程序与数据库与数据库之间的连接
conn = DriverManager.getConnection(url,user,password);
// 第三步:获取数据库操作对象
stmt = conn.createStatement();
// 第四步:执行sql语句
String mysql = "update dept set dname = '销售部' ,loc = '天津' where deptno = 20 ";
//可以写任意sql语句,但是处理其执行结果集时,查询语句会有所不同,会在下文展示如何处理查询语句结果集
int count = stmt.executeUpdate(mysql);
// 第五步:处理sql语句执行结果
System.out.println(count == 1 ? "修改成功" : "修改失败");
}catch(Exception e)
{
e.printStackTrace();
}finally {
// 第六步:释放资源
// 注:为了保证资源一定释放,在finally语句块中关闭资源;并且要遵循从小到大依次关闭,分别对其try...catch
try {
if(stmt != null) //先数据库操作对象
stmt.close();
}catch (SQLException e)
{
e.printStackTrace();
}
try {
if(conn != null) //后连接对象
conn.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
注册驱动的三种方法
方法一:多态,父类型引用指向子类型对象
Driver driver = new com.mysql.jdbc.properties.Driver();
DriverManager.registerDriver(driver);
System.out.println("数据库连接对象 = " + conn);
方法二:类加载 (常用)
String driver = "com.mysql.jbdc.properties.Driver";
Class.forName(driver);
方法三:使用资源绑定器配置文件
// 实际开发中常用:将连接数据库的所有信息配置到配置文件中 ,
// 不建议把连接数据库的信息写到java程序中
//使用资源绑定器绑定属性文件:此处文件名为:jdbc.properties 位于src的JDBC包下
ResourceBundle bundle = ResourceBundle.getBundle("JDBC/jdbc");
//注意:此处jdbc.properties 文件要放在该类下/src下,如果没有的话,就要使用绝对路径,其次在代码中不要加上jdbc.properties 文件其扩展名.properties
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
如何处理查询结果集
具体处理方式在第5.处理查询结果集详见
package JDBC;
import java.sql.*;
import java.util.ResourceBundle;
public class JDBCTest_Select {
public static void main(String[] args) {
//可以在这里编写多条sql语句:后续可以通过接口对象Statement接口 执行executeQuery()/executeUpdate()方法执行sql操作
String mysql1 = "SELECT deptno,dname,loc FROM dept;" ;
Statement stmt = null;
Connection conn = null;
ResultSet rs = null;
try {
// 1.注册驱动:类加载 (常用)
String driver = "com.mysql.jdbc.properties.Driver" ;
Class.forName(driver); //加载MySQL的JDBC驱动程序 反射机制
String url = "jdbc.properties:mysql://127.0.0.1:3306/databaseName";
String user = "root";
String password = "*****";
//2.获取连接:建立驱动程序与数据库与数据库之间的连接
conn = DriverManager.getConnection(url, user, password);
//3.获取数据库操作对象: 利用连接对象conn创建Statement接口对象stmt
stmt = conn.createStatement();
//4.执行sql
rs = stmt.executeQuery(mysql1);
// 5.处理查询结果集
{
//next():将光标从当前位置前移一行,若当前行有效,则返回true,若不存在下一行,则返回false
//ResultSet光标最初位于第一行之前
while(rs.next()) //利用循环语句对结果集rs的进行询问输出
{
// dname/deptno/loc是表中字段名(列名)
String en = rs.getString("dname");//也可rs.getString(2);数字表示表中第几列
int emp = rs.getInt("deptno");
String mgr = rs.getString("loc");
System.out.println(en + " " + emp + " " + mgr );
}
}
}catch(Exception e)
{
e.printStackTrace();
}finally {
//6.释放资源
try {
if (rs != null) //先查询结果集
rs.close();
}catch (SQLException e)
{
e.printStackTrace();
}
try {
if (stmt != null) //再数据库操作对象
stmt.close();
}catch (SQLException e)
{
e.printStackTrace();
}
try {
if (conn != null) //最后连接对象
conn.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
预编译(补充)
注:不是与上文连接的同一数据库
import java.sql.*;
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//useUnicode=true&characterEncoding=utf-8解决中文乱码问题
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "******";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
Connection connection = DriverManager.getConnection(url,username,password);
//3.向数据库发送SQL的对象Statement:CRUD
final Statement statement = connection.createStatement();
//4.编写SQL
/*
//4.编写SQL
* String sql = "select * from users";
*/
String sql = "insert into users(id ,name,password,email,birthday) values(?,?,?,?,?);";
//5.预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 4); //给第一个占位符? 的值赋值为4
preparedStatement.setString(2, "kuangshen"); //给第一个占位符? 的值赋值为kuangshen
preparedStatement.setString(3, "123456"); //给第一个占位符? 的值赋值为123456
preparedStatement.setString(4, "123@qq.com"); //给第一个占位符? 的值赋值为123@qq.com
preparedStatement.setDate(5, new Date(new java.util.Date().getTime())); //给第一个占位符? 的值赋值为 new Date(new java.util.Date().getTime())
/* //5.执行查询SQL,返回一个ResultSet : 结果集
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
System.out.println("id = " + rs.getObject("id"));
System.out.println("name = " + rs.getObject("name"));
System.out.println("password = " + rs.getObject("password"));
System.out.println("email = " + rs.getObject("email"));
System.out.println("birthday = " + rs.getObject("birthday"));
}
statement.close();
rs.close();
*/
//6.执行SQL
int i = preparedStatement.executeUpdate();
if (i > 0) {
System.out.println("插入成功@");
}
//关闭连接,释放资源,先开后关
preparedStatement.close();
connection.close();
}
}