1、代码实现:
import java.sql.*;
public class Tset1 {
public static void main(String[] args) {
//1、加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("驱动加载失败");
}
//2、获取链接
Connection conn=null;
try {
conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");
} catch (SQLException e) {
e.printStackTrace();
}
//3预编译SQL语句:
String sql="INSERT INTO `order1` ( ord_title, ord_phone, ord_date, ord_price, ord_address, ord_status )\n" +
"VALUES\n" +
"\t(?, ?, now(), ?, ?, 1 )";//?表示占位符,是一个参数
PreparedStatement pst=null;
try {
pst=conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
//4、传参
try {
pst.setObject(1,"袜子");
pst.setObject(2,"1516516565");
pst.setObject(3,"5");
pst.setObject(4,"篮球袜");
} catch (SQLException e) {
e.printStackTrace();
}
//5、执行DML
try {
int i=pst.executeUpdate();//返回一个整数,表示影响的行数
} catch (SQLException e) {
e.printStackTrace();
}
//6关闭连接释放资源
if( pst!=null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
2、事务(面试):
2.1什么是事务?
事务是指逻辑上的一组操作,组成这组操作的各个单元,要不全部成功,要不全部失败
2.2代码示例:手动一起提交
import java.sql.*;
public class Tset1 {
public static void main(String[] args) {
//1、加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("驱动加载失败");
}
//2、获取链接
Connection conn=null;
try {
conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");
} catch (SQLException e) {
e.printStackTrace();
}
//2.1设置为手动提交
//2.1设置为手动提交
try {
conn.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
//3预编译SQL语句:
String sql="INSERT INTO `order1` ( ord_title, ord_phone, ord_date, ord_price, ord_address, ord_status )\n" +
"VALUES\n" +
"\t(?, ?, now(), ?, ?, 1 )";//?表示占位符,是一个参数
//不需要写commit?默认情况下一个sql语句就是一个事务,一个sql就自动提交了,默认情况下不能保证事务
String sql2=".......";
// 如何保证多个SQL是在一个事务里面,要么全部成功,要么全部失败
PreparedStatement pst=null;
try {
pst=conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
//4、传参
try {
pst.setObject(1,"袜子");
pst.setObject(2,"1516516565");
pst.setObject(3,"5");
pst.setObject(4,"篮球袜");
} catch (SQLException e) {
e.printStackTrace();
}
//5、执行DML
try {
int i=pst.executeUpdate();//返回一个整数,表示影响的行数
} catch (SQLException e) {
e.printStackTrace();
}
//5.1提交事务
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
//6关闭连接释放资源
if( pst!=null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}