1.连接数据库时所用的几个对象
- DriverManager :管理jdbc驱动
- Connection:连接 通过(DriverManager产生)
- Statement(PreparedStatement):执行增删改 由Connection产生
- CallableStatement: 调用数据库中的存储函数 (通过Connection)
- Result: 返回结果集 由Statement产生
2.Connection产生操作数据库对象
- Connection产生Statement对象:Connection.createStatement()
- Connection产生PreparedStatement对象:prepareStatement()
3.Statement操作数据库
- 增删改 executeUpdate()
- 查询 executeQuery()
4.ResultSet结果集
- rs.next() 光标下移,判断是否有数据;
- previous(); true/false
- getString("字段名"/位置1 2 3) getint("字段名"/位置 1 2 3)
5.PreparedStatement操作数据库
- 增删改 executeUpdate()
- 查询 executeQuery()
- 赋值操作setString(位置,名字)
6.PreparedStatement和Statement执行时的区别
1.Statement:
sql;
executeUpdate(sql);2.PreparedStatement:
sql(可能存在占位符?)
在创建PrepareStatement对象时,将 sql预编译PreparedStatement(sql);
exectuUpdate()
7.执行实例
package JDBC;
import java.sql.*;
public class PreparedStatementDemo {
//URL:其中user表示向mysql中名为user的数据库写入数据(填入你的数据库名)
static String URL = "jdbc:mysql://localhost:3306/user";
//数据库的用户名
static String USERNAME = "root";
//数据库的密码
static String PWD = "密码";
public static void update() {// 增删改
Connection connection = null;
PreparedStatement pstmt =null;
// ResultSet rs=null; //查询的结果集 类似于一张表 rs指针默认指向结果集的前一行
//rs.next(); 1.下移 2.判断下移之后是否有数据 rs.getint() rs.getString() rs.getDate 获取数据
try {
// 1.导入驱动,加载具体的驱动类
Class.forName("com.mysql.cj.jdbc.Driver");// 加载具体的驱动类
// 2.与数据库建立连接
connection = DriverManager.getConnection(URL, USERNAME, PWD);
// 3.发送sql,执行(增删改、查)
//String sql ="select * from users";
//PreparedStatement的强大之处在于可以预编译sql语句 (可以在里面写问好)
String sql="insert into users values(?,?)";
//牢记:下面这句一定要写在set方法之前,不然会报空指针错误
pstmt=connection.prepareStatement(sql);
//同时可以用pstmt.setString方法设置位置的值
pstmt.setString(1,"李成虎");
pstmt.setString(2,"lchSiMaDongXi");
//rs=pstmt.executeQuery();
int count= pstmt.executeUpdate();
// 5.处理结果
if (count > 0) {
System.out.println("操作成功!");
}
/* while(rs.next()){
String sname=rs.getString("name");
String spwd=rs.getString("password");
System.out.println(sname+"--"+spwd);
} */
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
finally {
try {
//if(rs!=null) rs.close();
if(pstmt!=null) pstmt.close();// 对象.方法
if(connection!=null)connection.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
PreparedStatementDemo demo =new PreparedStatementDemo();
demo.update();
}
}