Mysql连接数据库:PreparedStatement.addBatch()方法
1.Eclipse连接MySQL数据库
mysql>CREATE DATABASE test; //创建一个数据库
mysql>use test; //指定test为当前要操作的数据库
mysql>CREATE TABLE user (name VARCHAR(20),password VARCHAR(20)); //创建一个表user,设置两个字段。
mysql>INSERT INTO user VALUES('huzhiheng','123456'); //插入一条数据到表中
2.驱动已经导入,下面我们来写一个程序验证一下
import java.sql.*;public class MysqlJdbc { public static void main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver"); //加载MYSQL JDBC驱动程序 //Class.forName("org.gjt.mm.mysql.Driver"); System.out.println("Success loading Mysql Driver!"); } catch (Exception e) { System.out.print("Error loading Mysql Driver!"); e.printStackTrace(); } try { Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test","root","198876"); //连接URL为 jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码 System.out.println("Success connect Mysql server!"); Statement stmt = connect.createStatement(); ResultSet rs = stmt.executeQuery("select * from user"); //user 为你表的名称 while (rs.next()) { System.out.println(rs.getString("name")); } } catch (Exception e) { System.out.print("get data error!"); e.printStackTrace(); } }}import java.sql.*;public class Myjproject { public static void main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver"); //加载MYSQL JDBC驱动程序 //Class.forName("org.gjt.mm.mysql.Driver"); System.out.println("Success loading Mysql Driver!"); } catch (Exception e) { System.out.print("Error loading Mysql Driver!"); e.printStackTrace(); } try { Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test","root","198876"); int num=100; PreparedStatement Statement=connect.prepareStatement("INSERT INTO user VALUES(?,?)"); for(int i=0;i<num;i++) //定义个100次的循环,往表里插入一百条信息。 { Statement.setString(1,"chongshi"+i); Statement.setString(2,"bo"+i); Statement.executeUpdate(); } // } catch (ClassNotFoundException e) { // TODO Auto-generated catch block // System.out.println("An error has occurred:"+e.toString()); // e.printStackTrace(); }catch(SQLException e) { } }}Connection connection =getConnection();
connection.setAutoCommit(false);
PreparedStatement statement = connection.prepareStatement("INSERT INTO TABLEX VALUES(?, ?)"); //记录1statement.setInt(1, 1); statement.setString(2, "Cujo"); statement.addBatch(); //记录2statement.setInt(1, 2); statement.setString(2, "Fred"); statement.addBatch(); //记录3statement.setInt(1, 3); statement.setString(2, "Mark"); statement.addBatch(); //批量执行上面3条语句. 一口吞了,很爽int [] counts = statement.executeBatch(); //Commit it 咽下去,到肚子(DB)里面connection.commit();