Linux Java串連MySQL資料庫

來源:互聯網
上載者:User

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 />}

執行結果:

完整源碼

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.