JDBC的本质
是一堆接口,sun公司定义的一套操作所有关系型数据库的规则。各个数据库厂商去实现这套接口,提供数据库驱动jar包。我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类。
JDBC使用步骤
1.注册驱动
2.获取数据库链接
3.获取数据库操作对象
4.执行sql语句
5.处理查询结果集(查询语句才需要)
6.关闭资源
增删改操作
public class JdbcDemo1 {
public static void main(String[] args) {
try {
// 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 获取数据库链接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/companytest?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false", "root", "123456");
// 获取数据库操作对象
Statement statement = conn.createStatement();
// 执行sql语句
int i = statement.executeUpdate("insert into dept (deptno,dname,loc) values (50,'销售部','上海')");
System.out.println(i);
// 关闭资源
statement.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
查询操作
@Test
public void testRead(){
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
try {
// 加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 获取数据库链接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/companytest?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false", "root", "123456");
// 获取数据库对象
statement= conn.createStatement();
// 执行sql语句
rs = statement.executeQuery("select deptno,dname,loc from dept ");
// 处理结果集
while (rs.next()){
System.out.println(rs.getString("deptno") + "--" + rs.getString("dname") + "--" + rs.getString("loc"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally { // 关闭资源
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
PreparedStatement
用Statement时,在where后加上“or 1 = 1”这种为true的句子,就能够轻松访问数据库,很危险,这种现象叫SQL注入。所以为了避免这种事的发生,引入了PrepareStatement这个类
该类中的方法
ps.setXxx(int,args);:用占位符的方式,来定义增删改查时被修改或者查询条件,避免SQL注入问题。其中Xxx是对应位置的参数类型
@Test
public void test2(){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
System.out.println("请输入用户名:");
Scanner name = new Scanner(System.in);
String username = name.next();
System.out.println("请输入密码:");
Scanner password = new Scanner(System.in);
int pass = password.nextInt();
ps = conn.prepareStatement("select empno,ename from emp where ename = ? and empno = ?");
ps.setString(1,username);
ps.setInt(2,pass);
rs = ps.executeQuery();
if (rs.next()){
System.out.println("登陆成功");
}else{
System.out.println("登陆失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.close(rs,ps,conn);
}
}