?? simpletest.java
字號:
package jdbcbook.ch04;
import java.sql.*;
// JDBC訪問數據庫的簡單例子
public class SimpleTest
{
// 定義驅動程序的名稱
public static final String drivername = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
// 定義數據庫的URL
public static final String url = "jdbc:microsoft:sqlserver://192.168.0.100:1433;DatabaseName=pubs;";
// 定義訪問數據庫的用戶名
public static final String user = "sa";
// 定義訪問數據庫的密碼
public static final String password = "12345";
public static void main( String[] args )
{
//設定查詢SQL語句
String queryString = "SELECT title, price FROM TITLES";
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try
{
// 1. 加載驅動程序
Class.forName( drivername );
// 2. 建立連接
conn = DriverManager.getConnection( url, user, password );
// 3. 創建Statement
st = conn.createStatement();
// 4. 執行SQL語句,獲得查詢結果
rs = st.executeQuery( queryString );
// 5. 輸出查詢結果
while( rs.next() )
{
System.out.println( "書名:" + rs.getString( "title" )
+ "(定價:" + rs.getDouble( "price" ) + ")" );
}
// 6. 關閉資源
rs.close();
st.close();
conn.close();
}
catch (Throwable t)
{
// 錯誤處理:輸出錯誤信息
t.printStackTrace( System.out );
}
finally
{
// finally子句總是會被執行(即使是在發生錯誤的時候)
// 這樣可以保證ResultSet,Statment和Connection總是被關閉
try
{
if (rs != null)
rs.close();
}
catch(Exception e) {}
try
{
if (st != null)
st.close();
}
catch(Exception e) {}
try
{
if (conn != null)
conn.close();
}
catch (Exception e){}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -