JDBC编程六步:
1.注册驱动 (告诉Java程序即将使用哪个数据库)
2.获取连接(JVM进程和数据库进程的通道打开,使用后必须关闭)
3.获取数据库操作对象(专门执行SQL语句的对象)
4.执行SQL语句(主要执行DQL,DML)
5.处理查询结果集(只有当第四步执行的是select语句时才有这一步)
6.释放资源(Java和数据库属于进程间的通讯,必须关闭)
Statement和PreparedStatement的区别:
1.前者存在sql注入,后者没有
2.前者是编译一次执行一次,后者编译一次执行多次
3.PreparedStatement会在编译阶段做类型的安全检查
如果只给sql传值,用后者;如果需要sql注入,用前者
代码样例
import java.sql.*;
public class JDBCTest02 {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //注册驱动
//注册驱动也可以写 Class.forName(“com.mysql.jdbc.Driver”);
connection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/mydatabase”,”root”,”y1475369”); //建立连接
statement = connection.createStatement(); //创建数据库操作对象
int count = statement.executeUpdate(“delete from dept where deptno = 50”); //执行SQL语句
System.out.println(count == 1 ? “save success” : “fail”);
} catch (SQLException e){
e.printStackTrace();
} finally {
if (statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} //释放资源
}
}
}