java連接數(shù)據(jù)庫(代碼分享)
更新時(shí)間:2017年03月24日 10:37:50 作者:LiangYun-Yin
本文主要介紹了java連接數(shù)據(jù)庫的實(shí)現(xiàn)方法代碼。具有很好的參考價(jià)值。下面跟著小編一起來看下吧
話不多說,請(qǐng)看代碼:
package com.shsxt.jdbcs;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
* jdbc步驟: java連接數(shù)據(jù)庫
* // 導(dǎo)入 jar包
* 1、加載驅(qū)動(dòng) 數(shù)據(jù)庫廠商提供的實(shí)現(xiàn)類
* 2、獲取連接 提供 url 用戶名 密碼
* 3、創(chuàng)建處理塊 可以發(fā)送SQL語句到服務(wù)器(數(shù)據(jù)庫) 準(zhǔn)備一條 SQL語句
* 4、結(jié)果集
* 5、分析結(jié)果集
* 6、釋放資源 先開的后放, 后打開的先放
*/
public class Demo002JDBCConnect {
public static void main(String[] args) throws ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String user= "scott";
String pwd= "tiger";
Connection conn = null;
Statement s = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(url, user, pwd);
s = conn.createStatement();
String sql = "select deptno, dname, loc from dept";
rs = s.executeQuery(sql);
while(rs.next()){
int deptno = rs.getInt(1); // 根據(jù)列號(hào)來獲取值
String dname = rs.getString("dname"); // 根據(jù)列名來獲取值
String loc = rs.getString(3);
System.out.println(deptno + "\t" + dname + "\t" + loc);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(s!=null){
try {
s.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持腳本之家!
您可能感興趣的文章:
- Java連接數(shù)據(jù)庫步驟解析(Oracle、MySQL)
- java使用dbcp2數(shù)據(jù)庫連接池
- Java數(shù)據(jù)庫連接池的幾種配置方法(以MySQL數(shù)據(jù)庫為例)
- java jdbc連接mysql數(shù)據(jù)庫實(shí)現(xiàn)增刪改查操作
- Java連接Sql數(shù)據(jù)庫經(jīng)常用到的操作
- Java使用JDBC連接數(shù)據(jù)庫的實(shí)現(xiàn)方法
- java配置dbcp連接池(數(shù)據(jù)庫連接池)示例分享
- java連接MySQl數(shù)據(jù)庫實(shí)例代碼
- Java Web項(xiàng)目中連接Access數(shù)據(jù)庫的配置方法
- java連接mysql數(shù)據(jù)庫亂碼的解決方法
相關(guān)文章
Spring AOP切點(diǎn)表達(dá)式使用及說明
這篇文章主要介紹了Spring AOP切點(diǎn)表達(dá)式使用及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
打開.properties中文顯示unicode編碼問題以及解決
這篇文章主要介紹了打開.properties中文顯示unicode編碼問題以及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01
手寫redis@Cacheable注解?參數(shù)java對(duì)象作為key值詳解
這篇文章主要介紹了手寫redis@Cacheable注解?參數(shù)java對(duì)象作為key值詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01

