在之前提到過Statement的三個問題
用PreparedStatement解決sql拼接
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
public class TestPrepareStatement {
public static void main(String [] args) throws Exception{
//1、鍵盤輸入
Scanner input = new Scanner(System.in);
System.out.println("請輸入名字");
String ename = input.nextLine();
System.out.println("請輸入電話");
String tel = input.nextLine();
System.out.println("請輸入性別");
String gender = input.nextLine();
System.out.println("請輸入薪資");
String salaryStr = input.nextLine();
double salary = Double.parseDouble(salaryStr);
//2、註冊驅動
Class.forName("com.mysql.jdbc.Driver");
//3、獲取驅動
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/1205db","root","123456");
//4、編寫sql語句
String sql = "insert into t_employee(ename,tel,gender,salary) VALUES(?,?,?,?)";
//5、創建PreparedStatement
// Statement st = conn.createStatement(); 換爲下面的PreparedStatement
PreparedStatement pst = conn.prepareStatement(sql);
// 先傳入sql,對帶?的sql進行預編譯
//6、把?的具體值傳進去
pst.setObject(1, ename);
pst.setObject(2, tel);
pst.setObject(3, gender);
pst.setObject(4, salary);
//7、執行更新sql
int len = pst.executeUpdate();//這裏不能在傳入sql了,如果傳入sql會對????進行sql語句執行
// 在存sql上面的相等於沒有設置
System.out.println(len>0?"添加成功":"添加失敗");
//8、關閉連接
pst.close();
conn.close();
input.close();
}
}
傳入sql報下面的錯,錯誤的sql語法:
int len = pst.executeUpdate(sql);