Jdbc連接數(shù)據(jù)庫的基本步驟,供大家參考,具體內(nèi)容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
package demo.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JdbcConn { /** *JDBC (Java Data Base Connectivity) 數(shù)據(jù)庫連接,有以下幾個(gè)步驟: *1.加載驅(qū)動(dòng)程序 Class.forName(driver); *2.創(chuàng)建連接對(duì)象 Connection con = DriverManager.getConnection(url,username,password); *3.創(chuàng)建sql語句的執(zhí)行對(duì)象 *4.執(zhí)行sql語句 *5.對(duì)執(zhí)行結(jié)果進(jìn)行處理 *6.關(guān)閉相關(guān)連接對(duì)象 (順序跟聲明的順序相反)。 */ public static void main(String[] args) { String mysqlDriver = "com.mysql.jdbc.Driver" ; String mysqlUrl = "jdbc:mysql://localhost:3306/mybase" ; String mysqlUser = "root" ; String mysqlPass = "111" ; String oracleDriver = "oracle.jdbc.driver.OracleDriver" ; String oracleUrl = "jdbc:oracle:thin:@localhost:1521:XE" ; String userName = "zl" ; String passWord = "444" ; String sql = "select ename from emp" ; try { Class.forName(oracleDriver); } catch (ClassNotFoundException e) { System.out.println( "找不到驅(qū)動(dòng)" ); e.printStackTrace(); } Connection conn = null ; try { conn = DriverManager.getConnection(oracleUrl, userName,passWord ); } catch (SQLException e) { System.out.println( "數(shù)據(jù)庫連接錯(cuò)誤" ); e.printStackTrace(); } Statement st = null ; try { st = conn.createStatement(); } catch (SQLException e) { System.out.println( "創(chuàng)建數(shù)據(jù)庫聲明類錯(cuò)誤" ); e.printStackTrace(); } boolean flag = false ; int rows = 0 ; ResultSet rs = null ; try { flag = st.execute(sql); rows = st.executeUpdate(sql); rs = st.executeQuery(sql); while (rs.next()){ //通過列的標(biāo)號(hào)來查詢數(shù)據(jù); String name =rs.getString( 1 ); //通過列名來查詢數(shù)據(jù) String name2 = rs.getString( "ename" ); System.out.println(name); } } catch (SQLException e) { System.out.println( "測(cè)試--" ); e.printStackTrace(); } //關(guān)閉數(shù)據(jù)連接對(duì)象 try { if (rs!= null ){ rs.close(); } if (st!= null ){ st.close(); } if (conn!= null ){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/tashaxing/p/7501526.html