Linux(Ubuntu平台)Java通過JDBC串連MySQL資料庫,與Windows平台類似,步驟如下:
下載 jdbc: mysql-connector-java-5.1.18.tar.gz
解壓 jdbc: tar -zxvf mysql-connector-java-5.1.18.tar.gz
配置 jdbc:cp mysql-connector-java-5.1.18-bin.jar /usr/local/jdk1.6.0_22/jre/lib/ext/
Java樣本:
private static String sql="select top, id, name, country, dtime from gametop800 where id=\"com.rovio.angrybirds\"";
public mysqlConnect(){<br />String dbDriver = "com.mysql.jdbc.Driver";<br />String url = "jdbc:mysql://localhost/top800";<br />String username = "root";<br />String password = "";</p><p>Statement mStatement = null;<br />ResultSet mResultSet = null;<br />Connection mConnection = null;</p><p>String sql = "select top, id, name, country, dtime from gametop800 where top<=20";</p><p>try{<br />Class.forName(dbDriver).newInstance();<br />mConnection = DriverManager.getConnection(url, username, password);<br />mStatement = mConnection.createStatement();<br />mResultSet = mStatement.executeQuery(sql);</p><p>try{<br />while(mResultSet.next()){<br />System.out.print(mResultSet.getInt(1) + "\t");<br />System.out.print(mResultSet.getString(2) + "\t");<br />System.out.print(mResultSet.getString(3) + "\t");<br />System.out.println(mResultSet.getString(4));<br />}<br />}catch (Exception e){<br />System.out.println("資料庫讀取錯誤! \n" + e.getMessage());<br />}<br />}catch (SQLException e){<br />System.out.println("串連資料庫錯誤: \n" + url + "\n" + e.getMessage());<br />}catch (Exception e){<br />e.printStackTrace();<br />}finally{<br />//mStatement.close();<br />//mConnection.close();<br />}<br />}
執行結果:
完整源碼