歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java高效操作MySQL

Java高效操作MySQL

日期:2017/3/1 10:09:25   编辑:Linux編程

Statement可以操作數據庫,但是,在需要做一些結構相似的操作時,PrepareStatement比Statement更高效。

在創建PrepareStatement的時候使用

prepareStatement(String sql),其中的sql中包含?來占位

PreparedStatement ps=(PreparedStatement) conn.prepareStatement("insert into student values(?,?,?)");

在執行SQL語句之前為每個問號賦值就行了。

使用ps.setXXX(int index,XXX xxx );

注意:index從1開始。代碼如下:

  1. import java.awt.Color;
  2. import java.awt.Frame;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import com.mysql.jdbc.Connection;
  6. import com.mysql.jdbc.PreparedStatement;
  7. import com.mysql.jdbc.Statement;
  8. public class Test {
  9. public static void main(String[] args) {
  10. try {
  11. Class.forName("com.mysql.jdbc.Driver");
  12. Connection conn=(Connection) DriverManager
  13. .getConnection("jdbc:mysql://110.178.168.220:3306/zhang", "root", "zhycheng");
  14. //Statement st=(Statement) conn.createStatement();
  15. PreparedStatement ps=(PreparedStatement) conn.prepareStatement("insert into student values(?,?,?)");
  16. for(int i=5;i<100;i++)
  17. {
  18. ps.setInt(1, i);
  19. ps.setString(2, "test"+i);
  20. ps.setString(3, "男");
  21. ps.executeUpdate();
  22. }
  23. ps.close();
  24. conn.close();
  25. } catch (Exception e) {
  26. // TODO Auto-generated catch block
  27. e.printStackTrace();
  28. }
  29. }
  30. }
Copyright © Linux教程網 All Rights Reserved