jdbc
是一种用于执行sql语句的java api加载驱动
Class.foranme("文件路径");
获取连接--
Connection con = null
try
{
con = DriverManager.getConnection("","root","lovo")
}catch(SQLException e){
e.printStackTrace();
}finally{
if (con != null){
try{
con.closs
}
}
}
///获取语句对象--Statment
Statment stat = con.creatStatment();
语句对象执行sql
int row stat.executeUpdate(sql);--返回一个int值
ResultSet rs= state.execute Query(sql) 查询
预编译语句--
preparedstatement 先把确定的sql交给数据库编译,再把值传入数据库再执行!
"?"占位符,只能替代值部分 。
String sql = "select * from emp where f_name = ? and pwd = ?";
preparedStatement ps = con.createStatement
ps.setString(1,name);//问号是什么类型就set什么类型 下标是从1开始的 ps.setString(第几个问号,值)
ps.setString(2,password);
使用情况,用户输入,做where条件的时候
事物--TestTransaction
将多条dml语句同时执行一个功能,要多条语句同时成功,这个功能才能实现
当我们需要多条dml语句一起执行的时候,首先开启事物
con.setAoutCommit(false)设置自动提交为false
sql1
sql2
预编译2条sql语句
ps1.executeupdate();
ps2.executeupdate();
con.commit();事物整体提交
进异常----
使用 con.rollback();事物回滚
获取新增记录的id
int row sata.executeupdate(sql,stat.return_generated_keys);
resultSet ks = stat.getgeneratedkeys();
while(ks.next()){
int pk = ks.getInt(1);
}
select 语句执行 executeQuery();
增删改 语句执行 executeupdate();