標籤:
做遊戲用戶端多一年多了,在大學學的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(); } } }}
至此串連和兩種不同的資料插入就已經完成了。。
java串連mysql資料庫執行個體