Java高效操作MySQL
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开始。代码如下:
import java.awt.Color;import java.awt.Frame;import java.sql.DriverManager;import java.sql.ResultSet;import com.mysql.jdbc.Connection;import com.mysql.jdbc.PreparedStatement;import com.mysql.jdbc.Statement;public class Test {public static void main(String[] args) { try {Class.forName("com.mysql.jdbc.Driver");Connection conn=(Connection) DriverManager.getConnection("jdbc:mysql://110.178.168.220:3306/zhang", "root", "zhycheng");//Statement st=(Statement) conn.createStatement();PreparedStatement ps=(PreparedStatement) conn.prepareStatement("insert into student values(?,?,?)");for(int i=5;i<100;i++){ps.setInt(1, i);ps.setString(2, "test"+i);ps.setString(3, "男");ps.executeUpdate();}ps.close();conn.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}