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();
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();
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();
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().doDelete(50);
}
}
