JDBC連線Oracle MySQL資料庫

2021-08-04 06:37:57 字數 2744 閱讀 3568

在連線資料庫時,並不是所有的情況都適合使用hibernate等框架,比如單獨寫乙個報表服務,就需要使用簡單高效的jdbc來連線:

1、資料庫連線jdbc原理 :

2、oracle---class.forname

class.forname("oracle.jdbc.oracledriver"); 

string url = "jdbc:oracle:thin:@localhost:1521:orcl";

string user = "scott"; 

string password = "tiger";  

connection conn;

conn = drivermanager.getconnection(url,user, password);

3、oracle---drivermanager

driver driver = new oracle.jdbc.driver.oracledriver();    

drivermanager.registerdriver(driver);

string url = "jdbc:oracle:thin:@localhost:1521:orcl";

string user = "scott"; 

string password = "tiger";    

connection conn = drivermanager.getconnection(url,user, password);

4、mysql---class.forname

class.forname("com.mysql.jdbc.driver"); 

string url = "jdbc:mysql://localhost:3309/hh";    

properties info = new properties();    

info.setproperty("user", "root"); 

info.setproperty("password", "root");    

connection conn; 

conn = drivermanager.getconnection(url, info);

5、mysql---drivermanager

driver driver = new com.mysql.jdbc.driver();    

drivermanager.registerdriver(driver);    

string url = "jdbc:mysql://localhost:3309/hh";    

properties info = new properties();    

info.setproperty("user", "root");    

info.setproperty("password", "root");    

connection conn = drivermanager.getconnection(url, info);

6、mysql---driver

driver driver = new com.mysql.jdbc.driver();    

string url = "jdbc:mysql://localhost:3309/hh";    

properties info = new properties();    

info.setproperty("user", "root");    

info.setproperty("password", "root");    

connection conn = driver.connect(url, info);

7、使用

connection con = null;// 建立乙個資料庫連線

preparedstatement pre = null;// 建立預編譯語句物件,一般都是用這個而不用statement

resultset result = null;// 建立乙個結果集物件

string sql = "select * from student where name=?";// 預編譯語句,「?」代表引數

pre = con.preparestatement(sql);// 例項化預編譯語句

pre.setstring(1, "劉顯安");// 設定引數,前面的1表示引數的索引,而不是表中列名的索引

result = pre.executequery();// 執行查詢,注意括號中不需要再加引數

while (result.next())

// 當結果集不為空時

system.out.println("學號:" + result.getint("id") + "姓名:"

+ result.getstring("name"));

8、關閉連線

finally   

if(stmt != null)

if(conn != null)

} catch (sqlexception e)

}

9、完整示例**:

10、mysql的jdbc連線資料庫參考:

11、idea環境下詳細實現過程:

JDBC連線出錯

在連線資料庫來運算元據時,出現如下錯誤資訊 org.springframework.beans.factory.xml.xmlbeandefinitionreader loading xml bean definitions from class path resource org springfr...

JDBC連線屬性

hibernate 需要進行資料庫訪問,因此必須設定連線資料庫的相關屬性。所有 hibernate 屬性的名字和語義都在 org.hibernate.cfg.environment 中定義。下面是關於 jdbc 連線配置中最重要的設定。hibernate.connection.driver clas...

JDBC連線屬性

hibernate 需要進行資料庫訪問,因此必須設定連線資料庫的相關屬性。所有 hibernate 屬性的名字和語義都在 org.hibernate.cfg.environment 中定義。下面是關於 jdbc 連線配置中最重要的設定。hibernate.connection.driver clas...