做游戲客戶端多一年多了,在大學學的java的SSH,基本上都忘完了,今天看了一下發現基本的連接數據庫的都忘了。。。太可怕了這遺忘的速度。
所以寫了個連接的例子吧。。安裝好mysql數據庫之后新建了兩張表tx1,tx2。接下來連接數據庫,往前面兩張表里插入數據。
首先是公共連接類:
TestConnection.java
package cn.wan; import java.sql.Connection; import java.sql.*; public class TestConnection { private String driver; private String url; private String dbName; private String password; Connection conn; Statement sta; PreparedStatement prepare; public TestConnection() { this.driver = "com.mysql.jdbc.Driver"; this.url = "jdbc:mysql://localhost:3306/tx"; this.dbName = "root"; this.password = "126"; } public Connection getConnection()throws Exception { try { Class.forName(driver); conn = DriverManager.getConnection(url, dbName, password); } catch (Exception e) { e.printStackTrace(); } return conn; } public void closeConn() { try { if(this.conn!=null) { this.conn.close(); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
使用Statement類向tx1中插入數據,值得注意的是tx1表的key是整型的,所以注意插入數據的寫法。。
package cn.wan; import java.sql.Connection; import java.sql.Statement; public class TestStatement { // private static TestConnection connection; public static void main(String[] args)throws Exception { Connection conn; Statement state = null; Long start = System.currentTimeMillis(); TestConnection connection =new TestConnection(); try { conn = connection.getConnection(); state = conn.createStatement(); // 需要使用100條sql語句來插入數據 for(int i= 0;i<100;i++) { int num= i; String str2 = "name"+i; state.executeUpdate("insert into tx1 values('"+num+"','str"+i+"')"); } System.out.println("使用Statement費時:"+(System.currentTimeMillis()- start)); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally { connection.closeConn(); if(state !=null) { state.close(); } } } }
使用PreparedStatement類向tx2表中插入數據,也要注意他的語句的寫法:
package cn.wan; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement; public class TestPrepared { public static void main(String[] args)throws Exception { String sqlString = "insert into tx2 values(?,?)"; Connection conn= null; PreparedStatement state = null; Long startLong = System.currentTimeMillis(); TestConnection connection = new TestConnection(); try { conn = connection.getConnection(); // 使用Connection來創建一個PreparedStatemet對象 state = conn.prepareStatement(sqlString); // 100次為PreparedStatemet的參數賦值,就能插入100條記錄 for(int i = 0;i<100;i++) { state.setInt(1, i); state.setString(2, i+""); state.executeUpdate(); } System.out.println("使用PreparedStatemet耗時:"+(System.currentTimeMillis()-startLong)); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { connection.closeConn(); if(state !=null) { state.close(); } } } }
至此連接和兩種不同的數據插入就已經完成了。。