首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > Mysql >

Java高效率操作MySQL

2012-10-05 
Java高效操作MySQLStatement可以操作数据库,但是,在需要做一些结构相的操作时,PrepareStatement比Statemen

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


热点排行