目录
一、JDBC的连接步骤
1、创建驱动
//1、创建驱动
Class.forName("com.mysql.jdbc.Driver");
2、建立链接
//2、创建链接
String url="jdbc:mysql://localhost:3306/school?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";
String user="root";
String password="123456";
//链接
Connection con=null;
con= DriverManager.getConnection(url,user,password);
3、创建执行对象
//3、创建执行对象,这里用预编译对象
PreparedStatement psta=null;
psta=con.prepareStatement("select * from student");
4、执行SQL语句
//4、执行SQL语句,并返回ResultSet对象
ResultSet resultSet = psta.executeQuery();
5、解析SQL结果
//5、解析SQL执行结果,这里直接打印了一下数据
while(resultSet.next()){
//列名赋值
// String sid=resultSet.getString("sid");
// String sName=resultSet.getString("sName");
// String sAge=resultSet.getString("sAge");
// String sSex=resultSet.getString("sSex");
// System.out.println("sid:"+sid+"sName:"+sName+"sAge:"+sAge+"sSex:"+sSex);
//列索引赋值
String sid=resultSet.getString(1);
String sName=resultSet.getString(2);
String sAge=resultSet.getString(3);
String sSex=resultSet.getString(4);
System.out.println("sid:"+sid+"sName:"+sName+"sAge:"+sAge+"sSex:"+sSex);
}
6、关闭资源
//6、关闭资源(按照从小到大的顺序关闭)
resultSet.close();
psta.close();
con.close();
二、JDBC的各种操作
Statement和PreparedStatement的几个方法,用法有些区别。
//获取普通执行者对象:
Statement sta=null;
sta=con.createStatement();
sta.executeQuery("select * from student where sid=?");
//获取预编译执行者对象:
PeparedStatement psta=null;
psta=con.prepareStatement("select * from student where sid=?");
psta.executeQuery();
1、execute()
可以执行各种Sql语句,增删改查都可以,如果要获取查询结果集,需要用getResultSet方法获取。
该方法返回boolean值。
2、executeUpdate()
可以执行增删改等操作。
返回值是int类型,表示影响的行数。
3、executeQuery()
专门用于执行Sql查询语句
返回值是ResultSet类型的结果集,可以用next()方法循环遍历打印出来。
注意:
三、JDBC工具包类
通过将jdbc封装成一个工具类,可以减少代码量,提高可扩展性和安全性。
private static Connection con=null;
//数据库属性
private static final String URL="jdbc:mysql://localhost:3306/school?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";
private static final String USER="root";
private static final String PASSWORD="123456";
//加载驱动(静态代码块)
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取链接
public static Connection getCon(){
if(con==null){
try {
con= DriverManager.getConnection(URL,USER,PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
}
return con;
}
//关闭所有链接
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//关闭con链接
public static void closeCon(){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//编写其他的方法