1.加载驱动,
2.建立连接
3.添加数据准备sql语句
4.(设置参数,很重要!)
5.处理结果
最后,关闭资源
以修改为例,代码如下
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class Textupdate {
public static void main(String[] args) {
// TODO Auto-generated method stub\
Scanner in=new Scanner(System.in);
Connection conn=null;
PreparedStatement pstmt=null;
System.out.println("请输入要修改的书籍编号:");
int bid=in.nextInt();
System.out.println("请输入修改后的书名:");
String bname=in.next();
System.out.println("请输入修改后的作者:");
String author=in.next();
System.out.println("请输入修改后的价格:");
double price=in.nextDouble();
System.out.println("请输入修改后的类型:");
String btype=in.next();
try {
//1加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2建立连接
String url="jdbc:mysql://127.0.0.1:3306/myweb";
conn=DriverManager.getConnection(url,"root","root");
//3添加数据
String sql="update book set bname=?,author=?,price=?,btype=? where bid=? ";
pstmt=conn.prepareStatement(sql);
//!设置参数!很重要!
pstmt.setString(1, bname);
pstmt.setString(2, author);
pstmt.setDouble(3, price);
pstmt.setString(4, btype);
pstmt.setInt(5,bid);
//4执行
int n=pstmt.executeUpdate();
//5处理结果
if(n>0){
System.out.println("修改成功!");
}else{
System.out.println("修改失败!");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关闭资源(关闭顺序与使用顺序相反)
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}