Java訪問資料庫的具體步驟:

weixin_41648325發表於2018-06-08

1.載入(註冊)資料庫
驅動載入就是把各個資料庫提供的訪問資料庫的API載入到我們程式進來,載入JDBC驅動,並將其註冊到DriverManager中,每一種資料庫提供的資料庫驅動不一樣,載入驅動時要把jar包新增到lib資料夾下,下面看一下一些主流資料庫的JDBC驅動加裁註冊的程式碼:
//Oracle8/8i/9iO資料庫(thin模式)
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
//Sql Server7.0/2000資料庫
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
//Sql Server2005/2008資料庫
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//DB2資料庫
Class.froName("com.ibm.db2.jdbc.app.DB2Driver").newInstance();
//MySQL資料庫
Class.forName("com.mysql.jdbc.Driver").newInstance();
2.建立連結
建立資料庫之間的連線是訪問資料庫的必要條件,就像南水北調調水一樣,要想調水首先由把溝通的河流打通。建立連線對於不同資料庫也是不一樣的,下面看一下一些主流資料庫建立資料庫連線,取得Connection物件的不同方式:
//Oracle8/8i/9i資料庫(thin模式)
String url="jdbc:oracle:thin:@localhost:1521:orcl";
String user="scott";
String password="tiger";
Connection conn=DriverManager.getConnection(url,user,password);
//Sql Server7.0/2000/2005/2008資料庫
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";
String user="sa";
String password="";
Connection conn=DriverManager.getConnection(url,user,password);
//DB2資料庫
String url="jdbc:db2://localhost:5000/sample";
String user="amdin"
String password=-"";
Connection conn=DriverManager.getConnection(url,user,password);
//MySQL資料庫
String url="jdbc:mysql://localhost:3306/testDB?user=root&password=root&useUnicode=true&characterEncoding=gb2312";
Connection conn=DriverManager.getConnection(url);
3. 執行SQL語句
資料庫連線建立好之後,接下來就是一些準備工作和執行sql語句了,準備工作要做的就是建立Statement物件PreparedStatement物件,例如:
//建立Statement物件
Statement stmt=conn.createStatement();
//建立PreparedStatement物件
String sql="select * from user where userName=? and password=?";
PreparedStatement pstmt=Conn.prepareStatement(sql);
pstmt.setString(1,"admin");
pstmt.setString(2,"liubin");
做好準備工作之後就可以執行sql語句了,執行sql語句:
String sql="select * from users";
ResultSet rs=stmt.executeQuery(sql);
//執行動態SQL查詢
ResultSet rs=pstmt.executeQuery();
//執行insert update delete等語句,先定義sql
stmt.executeUpdate(sql);
4.處理結果集
訪問結果記錄集ResultSet物件。例如:
while(rs.next)
{
out.println("你的第一個欄位內容為:"+rs.getString("Name"));
out.println("你的第二個欄位內容為:"+rs.getString(2));
}
5.關閉資料庫
依次將ResultSet、Statement、PreparedStatement、Connection物件關 閉,釋放所佔用的資源.例如:
rs.close();
stmt.clost();
pstmt.close();
con.close();

相關文章