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(); } }}出现上面结果,说明你连接数据库成功。
3。可以查看到MySQL里面的内容,那我们是不是想往MySQL中插入数据呢。
下面的例子,往MySQL的user表中插入100条数据
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) { } }}关于PreparedStatement.addBatch()方法
Statement和PreparedStatement的区别就不多废话了,直接说PreparedStatement最重要的addbatch()结构的使用.
1.建立链接,(打电话拨号 )
Connection connection =getConnection();
2.不自动 Commit (瓜子不是一个一个吃,全部剥开放桌子上,然后一口舔了)
connection.setAutoCommit(false);
3.预编译SQL语句,只编译一回哦,效率高啊.(发明一个剥瓜子的方法,以后不要总想怎么剥瓜子好.就这样剥.)
PreparedStatement statement = connection.prepareStatement("INSERT INTO TABLEX VALUES(?, ?)"); 4.来一个剥一个,然后放桌子上
//记录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();