Java Web學習之JDBC串連__Java

來源:互聯網
上載者:User
【怎麼建立JDBC串連】
首先要到官網mysql.com 下載 connector-j   然後解壓出來,把裡面有一個類型為 jar的檔案 拷到要建立串連的那個project裡,有個lib的檔案夾裡,就可以了。




接下來建立一個類,輸入以下變數:
String sql = " SELECT * FROM tbl_user";   //用於查詢資訊
Connection conn=null; //當前的資料庫連接
Statement st =null; //用於向資料庫發送語句
ResultSet rs = null; //結果集,封裝了從資料庫中查詢到的資料
然後按住 Ctrl+Shift+o  在彈出的視窗中選擇匯入的類:java.sql.Statement 點擊next,選擇 java.sql.Connection 點擊finish;
就import了相關的類:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;


import java.sql.DriverManager;


try {
Class.forName("com.mysql.jdbc.Driver");         //註冊mysql的jdbc的驅動程式,forName方法初始化參數指定的類,並建立一個對應的樣本對象,參數中的字串是mysql中jdbc的驅動程式
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root","");  //擷取mysql的資料庫連接,第一個參數是mysql的URL 包括資料庫的主機名稱連接埠號碼和資料庫名字,第二個參數是mysql的使用者名稱,第三個參數是mysql的密碼

st = conn.createStatement();  //建立一個Statement的對象
rs=st.executeQuery(sql);        //發送mysql語句,返回結果集

while(rs.next())                    //用於遍曆結果集
{
System.out.print(rs.getInt("id")+"  ");     //各個get方法用於擷取資料庫中不同類型的值
System.out.print(rs.getString("name")+"  ");
System.out.print(rs.getString("password")+"  ");
System.out.print(rs.getString("email")+"  ");
System.out.println();
}

} catch (Exception e) {
e.printStackTrace();

}finally{                            //資源的清理工作,按照一定次序關閉各個資料項目

try {
rs.close();                   //由小到大的順序關閉
} catch (Exception e2) {
}

try {
st.close();
} catch (Exception e2) {
}

try {
conn.close();
} catch (Exception e2) {
}
}




編寫完成後,點擊右鍵,run as Java Application

聯繫我們

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