您的位置:首页 > 博客中心 > 数据库 >

JDBC连接访问SQL Server2012

时间:2022-03-14 15:49

 1 package com.pkg1;
 2 
 3 import java.sql.*;
 4 import com.microsoft.sqlserver.jdbc.*;
 5 
 6 public class JdbcDemo2 {
 7     Connection conn;
 8     PreparedStatement st;
 9     final static String connUrl = "jdbc:sqlserver://127.0.0.1:1433;databaseName=TestDB";
10     final static String dbUserName = "sa";
11     final static String dbPwd = "123456";
12     
13     public JdbcDemo2(){
14         try{
15             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
16             this.conn = DriverManager.getConnection(connUrl, dbUserName, dbPwd);
17         }catch(Exception e){
18             e.printStackTrace();
19             this.close();
20         }
21     }
22     
23     public ResultSet runQuery(String sql){
24         ResultSet rs = null;
25         try{
26             this.st = this.conn.prepareStatement(sql);
27             rs = this.st.executeQuery();
28         }catch(Exception e){
29             this.close();
30             return null;
31         }
32         
33         return rs;
34         
35     }
36     
37     public void close(){
38         try{
39             if(this.st != null){
40                 this.st.close();
41             }
42             
43             if(this.conn != null){
44                 this.conn.close();
45             }
46         }catch(Exception e){
47             e.printStackTrace();
48         }
49     }
50     
51 }

 

本类排行

今日推荐

热门手游