package Inster_Demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class pstmtInsert_test {
public static final String DBDRIVER = "com.mysql.jdbc.Driver" ;
public static final String DBURL ="jdbc:mysql://localhost:3306/emp01?serverTimezone=UTC&serverTimezone=GMT&characterEncoding=utf8&useServerPrepStmts=true";
public static final String DBUSER = "root";
public static final String DBPASS = "123456";
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs = null;
public void getConnection() {
try {
Class.forName(DBDRIVER) ;// 加载驱动程序
} catch (ClassNotFoundException e) {
System.out.println(e);
System.out.print("DBDRIVER----------No");
}
try{
conn=DriverManager.getConnection(DBURL,DBUSER,DBPASS);
}catch(Exception e1){
System.out.println(e1);
System.out.print("conn---no");
}
}
public void pstmtInsert() {
getConnection();
String sql ="insert into emp(empno,ename,job,hiredate,sal) values(?,?,?,?,?)";
try{
pstmt=conn.prepareStatement(sql); //先执行这句 不能先执行设置占位符的值!
}catch(Exception e2){
System.out.print(e2);
System.out.println("pstmt-----on");
}
try {
pstmt.setInt(1,6666);
pstmt.setString(2, "徐晓");
pstmt.setString(3, "ceo");
pstmt.setDate(4, new java.sql.Date(0));
pstmt.setFloat(5, (float) 1000.2);
} catch (SQLException e) {
e.printStackTrace();
System.out.println("pstmt拼接错误");
}
try {
pstmt.executeUpdate(); // 重点!!!!!!! stmt.executeUpdate(sql); 不然执行不了sql语句
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void pstmtSelect() {
getConnection();
String sql="SELECT * FROM emp where empno='6666'";
try {
pstmt=conn.prepareStatement(sql);
} catch (SQLException e1) {
e1.printStackTrace();
}
try{
rs=pstmt.executeQuery();
System.out.println("rs-----yes");
}catch(Exception e3){
System.out.println(e3);
System.out.println("rs-----no");
}
try {
while(rs.next()){
try {
System.out.println( rs.getInt(1));
} catch (SQLException e) {
e.printStackTrace();
}
try {
System.out.println( rs.getString(2));
} catch (SQLException e) {
e.printStackTrace();
}
try {
System.out.println( rs.getString(3));
} catch (SQLException e) {
e.printStackTrace();
}
try {
System.out.println( rs.getDate(4));
} catch (SQLException e) {
e.printStackTrace();
}
try {
System.out.println( rs.getFloat(5));
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
pstmtInsert_test t= new pstmtInsert_test();
t.pstmtInsert();
t.pstmtSelect();
}
}