package test0813;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Test02 {
public void doSelect(int Id) {
// 根据主键查询
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/emp?characterEncoding=utf-8",
"root", "root");
PreparedStatement pst = con.prepareStatement("select * from dept where Id=?");
pst.setInt(1, Id);// 给第一个问号传了值
ResultSet rs = pst.executeQuery();
if (rs.next()) {
// 如果有下一行才输出,不会报空指针异常
System.out.println(rs.getInt("Id") + "\t" + rs.getString("dname") + "\t" + rs.getString("loc"));
}
rs.close();
pst.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doInsert(int Id, String dname, String loc) {
// 插入
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/emp?characterEncoding=utf-8",
"root", "root");
PreparedStatement pst = con.prepareStatement("insert into dept values(?,?,?)");
pst.setInt(1, Id);// 给第一个问号传了值
pst.setString(2, dname);
pst.setString(3, loc);
int result = pst.executeUpdate();// 增删改都用update
if (result > 0) {
System.out.println("ok");
} else {
System.out.println("error");
}
pst.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doUpdate(int Id, String dname, String loc) {
// 更新
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/emp?characterEncoding=utf-8",
"root", "root");
PreparedStatement pst = con.prepareStatement("update dept set dname=?,loc=? where Id=?");
pst.setString(1, dname);
pst.setString(2, loc);
pst.setInt(3, Id);
int result = pst.executeUpdate();// 增删改都用update
if (result > 0) {
System.out.println("ok");
} else {
System.out.println("error");
}
pst.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doDelete(int Id) {
// 删除,一般按主键
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/emp?characterEncoding=utf-8",
"root", "root");
PreparedStatement pst = con.prepareStatement("delete from dept where Id=?");
pst.setInt(1, Id);
int result = pst.executeUpdate();// 增删改都用update
if (result > 0) {
System.out.println("ok");
} else {
System.out.println("error");
}
pst.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// new Test02().doSelect(10);
// new Test02().doInsert(50, "技术部", "沈阳市");
// new Test02().doUpdate(50, "技术1部", "大城市");
new Test02().doDelete(50);
}
}
eclipse连接数据库 进行增删改查操作
猜你喜欢
转载自blog.csdn.net/gcyqweasd/article/details/110198843
今日推荐
周排行