为了测试mysql的索引,要向数据库先插入上万条数据,然后再测试。手动插入太麻烦,写了一段代码。
先上代码:
package action; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class InsertData { public Connection getConnection(){ // 驱动程序名 String driver = "com.mysql.jdbc.Driver"; // URL指向要访问的数据库名scutcs String url = "jdbc:mysql://127.0.0.1:3306/wang"; // MySQL配置时的用户名 String user = "root"; // MySQL配置时的密码 String password = "12345"; Connection conn=null; try { // 加载驱动程序 Class.forName(driver); // 连续数据库 conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace();// TODO: handle exception } return conn; } public int insertData(int count,String value) throws SQLException{ InsertData insertData=new InsertData(); Connection conn=insertData.getConnection(); if(!conn.isClosed()) System.out.println("begin insert!"); // statement用来执行SQL语句 Statement statement = conn.createStatement(); // 要执行的SQL语句 int n=0; for (int i = 0; i <=count; i++) { String sql = "insert into student(Sno,Sname) values('"+i+"','"+value+"')"; n=statement.executeUpdate(sql); n++; } System.out.println("insert end!"); return n; } /** * @param args * @throws SQLException */ public static void main(String[] args) throws SQLException { // TODO Auto-generated method stub InsertData insertData=new InsertData(); Connection conn=insertData.getConnection(); if(!conn.isClosed()) System.out.println("Succeeded connecting to the Database!"); int n=0; n=insertData.insertData(10000,"数据内容"); System.out.println("the Count is:"+n); // statement用来执行SQL语句 Statement statement = conn.createStatement(); // 要执行的SQL语句 String sql = "select * from student"; // 结果集 ResultSet rs = statement.executeQuery(sql); System.out.println("-----------------"); System.out.println("执行结果如下所示:"); System.out.println("-----------------"); System.out.println(" 学号" + " " + " 姓名"); System.out.println("-----------------"); String name = null; while(rs.next()) { name = rs.getString("sname"); System.out.println(rs.getString("Sno") + " " + name); } rs.close(); conn.close(); } }
这样插入数据太慢了,不知道是程序慢,还是数据库太慢。这个回去再研究,等待下文。