Java jdbc使用步骤与常用方法

使用步骤

  1. 注册驱动
  2. 获取连接
  3. 定义sql语句
  4. 获取执行sql的对象
  5. 执行sql
  6. 处理
  7. 释放资源 遵循先开的后释放
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
String url = "jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=UTF-8";//此处mydb为我要连接的数据库
String username = "root";
String password = "123";
Connection conn = DriverManager.getConnection(url, username, password);

//3.定义sql语句
String sql = "insert into member values('张三6号','123','男','2003-11-02','编程','无','本科');";
String sql1 = "select * from member;";
String sql2 = "delete from member where name = '张三'";
String sql3 = "update member set password = '12345' where name='张三4号';";

//4.获取执行sql的对象 Statement
Statement stmt = conn.createStatement();

//5.执行sql
int count = stmt.executeUpdate(sql);//受影响的行数
int cnt2 = stmt.executeUpdate(sql2);
int cnt3 = stmt.executeUpdate(sql3);

//6.处理
System.out.println(count);
//7.释放资源 先开的后释放
stmt.close();
conn.close();

DriverManager

//获取连接
DriverManager.getConnection(url, username, password)

Connection (接口)

获取执行sql对象

Connection conn = DriverManager.getConnection(url, username, password);

处理事务

String sql3 = "update member set password = '12345' where name='张三4号';";
String sql4 = "update member set password = '123456' where name='张三6号';";
try {
    //开启事务
    conn.setAutoCommit(false);
    int cnt3 = stmt.executeUpdate(sql3);
    System.out.println(cnt3);
    int i = 3/0;
    int cnt4 = stmt.executeUpdate(sql4);
    System.out.println(cnt4);
    //提交事务
    conn.commit();
} catch(Exception e) {
    //回滚事务
    conn.rollback();
    e.printStackTrace();
}

事务中出现异常,回滚事务,出现异常的地方之前的操作不生效。
在这里插入图片描述

PreparedStatement

继承自Statement

1.预编译,提高性能

需要开启,在url后加上 useServerPrepStmts=true

String url = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8&useServerPrepStmts=true";

2.防止sql注入

//sql中的参数值用?代替
String sql = "select * from tb_user where username = ? and password = ?";
	//获取 PreparedStatement 对象
PreparedStatement pstmt =  conn.prepareStatement(sql);

//设置 ? 的值
pstmt.setString(1,name);
pstmt.setString(2,pswd);

//执行sql
ResultSet rs = pstmt.executeQuery();//不需要再传递sql

防sql注入:将敏感字符转义

String sql = "select * from tb_user where username='"+name+"' and password='"+pswd+"';";

password 输入 ’ or ‘1’ = '1 , 能够操作成功。

原因:字符串拼接,

select * from tb_user where username = 'zhangsan' and password = '' or '1'='1'

or后面的 ‘1’='1’为恒等式。

ResultSet

查询操作,返回结果集

ResultSet rs = stmt.executeQuery(sql);

访问结果集

while(rs.next()) {
    
    String name = rs.getString(1);
    String passwd = rs.getString(2);
    String sex = rs.getString(3);

}

你可能感兴趣的:(Java,java,开发语言)