Statement和Preparedment都是用来实现数据库连接的API接口,下面我们对两者的实现方式分别进行介绍
一.Statement
概述
statement用于执行一些简单的静态SQL语句,并返回它所生成的结果对象
-
接口:
public interface Statement extends Wrapper
-
在默认情况下,同一时间内每个Statement对象只能打开一个ResultSet对象.因此,如果读取一个ResultSet对象与另一个交叉,则这两个对象必须是由不同的Statement对象生成的.
实现步骤
1.加载mysql驱动类
2.建立与数据库连接,并返回连接对象
3.向数据库发送sql
4.关闭数据库连接
来看一下实际操作:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/*
使用Statement接口执行SQL语句
*/
public class Demo2 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/schooldb?serverTimezone = Asia/Shanghai","root","111");
Statement statement = connection.createStatement();
String name = "赵六";
String gender = "女";
String phone = "159";
String no = "5";
//修改操作
//statement.executeUpdate("Update student set name = '"+name+"',gender = '"+gender+"'"+"where no = "+no);
//删除操作
statement.executeUpdate("delete from student where no ="+no);
statement.close();
connection.close();
}
}
二.PreparedStatement
概述
PreparedStatement表示预编译的SQL语句的对象.相比于Statement我们更常使用 PreparedStatement来实现java与数据库的连接操作
-
接口:
public interface PreparedStatement extends Statement
* 即说明PreparedStatement是继承于Statement的
-
在此接口中,SQL语句被预编译存储在PreparedStatement对象中,然后可以使用此对象多次高效的执行该语句
实现步骤
1.加载mysql驱动类
2.建立与数据库连接,并返回连接对象
3.向数据库发送sql
4.关闭数据库连接
来看一下实际操作
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/*
使用PreparedStatement接口实现SQL语句
*/
public class Demo3 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/schooldb?serverTimezone = Asia/Shanghai","root","111");
String name = "Lisa";
String gender = "男";
String phone = "157";
String no = "9";
//预编译方式,预先将SQL及参数预编译到PreparedStatement对象中
//增添语句
/*PreparedStatement ps = connection.prepareStatement("insert into student(name,gender,phone)"+
"value (?,?,?)");
ps.setObject(1,name);
ps.setObject(2,gender);
ps.setObject(3,phone);
ps.executeUpdate();//执行*/
/*//修改语句`
PreparedStatement ps = connection.prepareStatement("update student set name=?,gender=?,phone=?"+"where no = ?");
ps.setObject(1,name);
ps.setObject(2,gender);
ps.setObject(3,phone);
ps.setObject(4,no);
ps.executeUpdate();*/
//删除语句
PreparedStatement ps = connection.prepareStatement("delete from student where no=?");
ps.setObject(1,no);
ps.executeUpdate();
ps.close();
connection.close();
}
}