mport 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.1.2:1433;DatabaseName=pubs;";
    // 定义访问数据库的用户名
    public static final String user = "sa";
    // 定义访问数据库的密码
    public static final String password = "123";
    public static void main( String[] args )
    {
        //设定查询SQL语句
        String queryString = "SELECT * 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){} 
        }
    }
}
[此贴子已经被作者于2006-12-6 11:34:44编辑过]

 
											





 
	    

