package JDBC_1;标签:ps,Exception,JDBC,改查,System,sql,println,基本操作,coon From: https://www.cnblogs.com/qin99/p/16808258.html
//演示jdbc所使用的预编译
import java.sql.*;
public class jdbc_2 {
private static Connection coon = null;
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
coon = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/jdbc_4", "root", "root"
);
} catch (Exception e) {
System.out.println("数据库连接失败");
}
}
public static void main(String[] args) throws Exception {
System.out.println(coon);
//数据库操作
//查询
select(coon);
//增加调用
insert();
select(coon);
//修改调用
update();
select(coon);
//删除调用
delete();
select(coon);
}
//删除用法
public static void delete() {
String sql = "delete from user where id =?";
PreparedStatement ps = null;
try {
ps = coon.prepareStatement(sql);
//后面的数字是表示删除ID为几的行列
ps.setInt(1, 1);
} catch (Exception e) {
System.err.println("SQL预处理失败");
}
try {
ps.execute();
} catch (Exception e) {
e.printStackTrace();
System.out.println("删除陈功了");
}
}
//修改
public static void update() {
String sql = "update user set nane =?," + " phone=?,em=? where id=? ";
PreparedStatement ps = null;
try {
ps = coon.prepareStatement(sql);
ps.setString(1, "小六子");
ps.setString(2, "66666");
ps.setString(3, "333");
ps.setInt(4, 6);
ps.execute();
} catch (Exception e) {
System.err.println("sql修改解析异常");
}
try {
ps.execute();
} catch (Exception e) {
e.printStackTrace();
System.out.println("修改失败");
}
}
//增加
public static void insert() {
String sql = "insert into user (nane,phone,em) value (?,?,?)";
PreparedStatement ps = null;
//获取编译对象并对sql语句进行预处理
try {
ps = coon.prepareStatement(sql);
ps.setString(1, "小阿涛");
ps.setString(2, "175");
ps.setString(3, "999");
} catch (Exception e) {
System.out.println("SQL预处理异常");
}
try {
ps.execute();
} catch (Exception e) {
e.printStackTrace();
System.out.println("SQl执行异常");
}
}
public static void select(Connection connection) throws Exception {
//3:操作数据库
//3.1查询
String sql = "select * from user";
//sql操作器
//获取sql操作器
Statement statement = connection.createStatement();
//3.3使用操作器执行查询并获取结果集
ResultSet resultSet = statement.executeQuery(sql);
//3.4解析结果集
System.out.println("id \t nane \tphone \tem");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String nane = resultSet.getString("nane");
String phone = resultSet.getString("phone");
String em = resultSet.getString("em");
System.out.println(id + "\t" + nane + "\t" + phone + "\t" + em);
}
}
}