對mysql資料的串連操作和關閉

來源:互聯網
上載者:User

標籤:

操作步驟:

1.載入資料庫驅動(先在工程裡載入資料庫對應的驅動包)

2.擷取串連

3.根據串連建立一個可執行sql的對象

4.執行sql語句

5.關閉串連

代碼:

package database;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class MysqlTest {    public static void main(String[] args) {        Connection conn = null;        Statement stmt = null;        ResultSet rs = null;        try {//載入驅動            Class.forName("com.mysql.jdbc.Driver");        } catch (ClassNotFoundException e) {            e.printStackTrace();        }        try {//擷取串連 jdbc:mysql:// 這一段是固定格式,localhost是伺服器位址,3306是連接埠,伺服器安裝的時候配置的,root是使用者名稱,寫死的,密碼是安裝伺服器的時候配置的。             conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata","root","");        } catch (SQLException e) {            e.printStackTrace();        }        try {//根據串連擷取一個執行sql語句的對象            stmt = conn.createStatement();        } catch (SQLException e) {            e.printStackTrace();        }        try {//執行sql語句            rs = stmt.executeQuery("select * from dept");        } catch (SQLException e) {            e.printStackTrace();        }        try {//列印表裡的內容,下標從1開始            while(rs.next()){                System.out.print(rs.getString(1)+" ");                System.out.print(rs.getString(2)+" ");                System.out.print(rs.getString(3));                System.out.println();            }        } catch (SQLException e) {            e.printStackTrace();        }        try {//關閉串連            conn.close();        } catch (SQLException e) {            e.printStackTrace();        }    }}

 

對mysql資料的串連操作和關閉

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.