八、JDBC——1-JDBC的典型用法
1-JDBC的典型用法
1.常用接口和类简介
(1)DriverManeger:
用于管理JDBC驱动的服务类,程序中使用该类获取Connection对象;
(2)Connection:
代表数据库连接对象,每个Connceion代表一个物理连接会话。想要访问数据库必须先获得数据库连接。
(3)Statement:
用于执行SQL语句的接口。该对象既可以用于执行DDL语句、DCL语句,也可以用于执行DML语句,还可以用于执行SQL的查询语句。
(4)PreparedStatement:
预编译的Statement对象。PreparedStatement是Statement的子接口,它允许数据库预编译SQL语句(这些SQL语句通常带有参数),以后每次只改变SQL命令的参数,避免数据库每次都要编译SQL语句,性能更好。使用PreparedStatement执行SQL语句时,无须再传入SQL语句,只要为预编译的SQL语句传入参数即可。
(5)使用示例:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCTest {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver"); //加载数据库驱动
//DriverManager使用:获取数据库连接Connection
//Connection:一个Connection代表一个数据库物理连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test",
"root",
"stx12345");
//通过Connection对象获取Statement对象或者PreparedStatement对象
//PreparedStatement是Statement的子接口
Statement stat = conn.createStatement();
//Statement对象或者PreparedStatement对象都是用于执行SQL语句
//PreparedStatement可以执行预编译的SQL语句
//Statement执行SQL语句的方法:
//executeUpdate()方法可以执行DML语句 也可以执行DDL语句
// stat.executeUpdate("create table test1("
// + "t_id int primary key auto_increment,"
// + "t_name varchar(255) not null,"
// + "t_age int not null"
// + ")"); //执行DDL语句
// //执行DML语句,插入记录
// stat.executeUpdate("insert into test1 (t_name,t_age) values ('testname1',18)");
// stat.executeUpdate("insert into test1 (t_name,t_age) values ('testname2',18)");
//ResultSet 结果集对象;
//执行Statement的查询方法,获取结果集对象
ResultSet rs = stat.executeQuery("select * from test1;");
//也可以使用execute()方法进行查询,execute()可以执行所有的SQL语句,但如果执行的是查询语句返回的是boolean类型
// System.out.println("test表中是否有记录:"+stat.execute("select * from test1"));
//遍历结果集
while(rs.next()){
System.out.println(rs.getInt(1)+"|"+rs.getString(2)+"|"+rs.getInt(3));
}
}
}
2.JDBC编程步骤
(1)使用反射加载数据库驱动;
(2)通过DriverManager获取Connection(数据库连接);
(3)通过Connection创建Statement对象;
(4)使用Statement执行SQL语句;
(5)如果执行的为查询语句则获取ResultSet;
(6)通过ResultSet获取想要获取的数库;
(7)关闭数据库资源,包括ResultSet、Statement和Connection。