1.連接數(shù)據(jù)庫(kù)時(shí)所用的幾個(gè)對(duì)象
- DriverManager :管理jdbc驅(qū)動(dòng)
- Connection:連接 通過(guò)(DriverManager產(chǎn)生)
- Statement(PreparedStatement):執(zhí)行增刪改 由Connection產(chǎn)生
- CallableStatement: 調(diào)用數(shù)據(jù)庫(kù)中的存儲(chǔ)函數(shù) (通過(guò)Connection)
- Result: 返回結(jié)果集 由Statement產(chǎn)生
2.Connection產(chǎn)生操作數(shù)據(jù)庫(kù)對(duì)象
- Connection產(chǎn)生Statement對(duì)象:Connection.createStatement()
- Connection產(chǎn)生PreparedStatement對(duì)象:prepareStatement()
3.Statement操作數(shù)據(jù)庫(kù)
- 增刪改 executeUpdate()
- 查詢 executeQuery()
4.ResultSet結(jié)果集
- rs.next() 光標(biāo)下移,判斷是否有數(shù)據(jù);
- previous(); true/false
- getString("字段名"/位置1 2 3) getint("字段名"/位置 1 2 3)
5.PreparedStatement操作數(shù)據(jù)庫(kù)
- 增刪改 executeUpdate()
- 查詢 executeQuery()
- 賦值操作setString(位置,名字)
6.PreparedStatement和Statement執(zhí)行時(shí)的區(qū)別
1.Statement:
sql;
executeUpdate(sql);2.PreparedStatement:
sql(可能存在占位符?)
在創(chuàng)建PrepareStatement對(duì)象時(shí),將 sql預(yù)編譯PreparedStatement(sql);
exectuUpdate()
7.執(zhí)行實(shí)例
package JDBC;
import java.sql.*;
public class PreparedStatementDemo {
//URL:其中user表示向mysql中名為user的數(shù)據(jù)庫(kù)寫入數(shù)據(jù)(填入你的數(shù)據(jù)庫(kù)名)
static String URL = "jdbc:mysql://localhost:3306/user";
//數(shù)據(jù)庫(kù)的用戶名
static String USERNAME = "root";
//數(shù)據(jù)庫(kù)的密碼
static String PWD = "密碼";
public static void update() {// 增刪改
Connection connection = null;
PreparedStatement pstmt =null;
// ResultSet rs=null; //查詢的結(jié)果集 類似于一張表 rs指針默認(rèn)指向結(jié)果集的前一行
//rs.next(); 1.下移 2.判斷下移之后是否有數(shù)據(jù) rs.getint() rs.getString() rs.getDate 獲取數(shù)據(jù)
try {
// 1.導(dǎo)入驅(qū)動(dòng),加載具體的驅(qū)動(dòng)類
Class.forName("com.mysql.cj.jdbc.Driver");// 加載具體的驅(qū)動(dòng)類
// 2.與數(shù)據(jù)庫(kù)建立連接
connection = DriverManager.getConnection(URL, USERNAME, PWD);
// 3.發(fā)送sql,執(zhí)行(增刪改、查)
//String sql ="select * from users";
//PreparedStatement的強(qiáng)大之處在于可以預(yù)編譯sql語(yǔ)句 (可以在里面寫問(wèn)好)
String sql="insert into users values(?,?)";
//牢記:下面這句一定要寫在set方法之前,不然會(huì)報(bào)空指針錯(cuò)誤
pstmt=connection.prepareStatement(sql);
//同時(shí)可以用pstmt.setString方法設(shè)置位置的值
pstmt.setString(1,"李成虎");
pstmt.setString(2,"lchSiMaDongXi");
//rs=pstmt.executeQuery();
int count= pstmt.executeUpdate();
// 5.處理結(jié)果
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();// 對(duì)象.方法
if(connection!=null)connection.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
PreparedStatementDemo demo =new PreparedStatementDemo();
demo.update();
}
}