JDBC链接sqlserver数据库

来源:互联网 发布:aa录音软件官方下载 编辑:程序博客网 时间:2024/05/17 23:00

1、下载Microsoft JDBC Driver 4.0 for SQL Server

在这里下载:http://www.microsoft.com/zh-cn/download/details.aspx?id=11774

4.0版本支持的 SQL Server有:

Microsoft®SQL Server® 2012

Microsoft®SQL Server® 2008 R2

Microsoft®SQL Server® 2008

Microsoft®SQL Server® 2005

Microsoft®SQL Azure

 

下载sqljdbc_4.0.2206.100_chs.tar.gz(2.2M),解压文件,得到sqljdbc.jar和sqljdbc4.jar。如果你使用的是jre1.7版本,则忽略sqljdbc.jar(因为它用不了,而且如果和sqljdbc4.jar一起用会出错),只留下sqljdbc4.jar。

2.jdbc代码

package jdbc;import java.sql.*;public class Connect { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";   static final String DB_URL = "jdbc:sqlserver://localhost:1433;DatabaseName=qdpuberp"; //  Database credentials static final String USER = "sa"; static final String PASS = "123";  public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{    //STEP 2: Register JDBC driver    Class.forName(JDBC_DRIVER);    //STEP 3: Open a connection    System.out.println("Connecting to database...");    conn = DriverManager.getConnection(DB_URL,USER,PASS);    //STEP 4: Execute a query    System.out.println("Creating statement...");    stmt = conn.createStatement();    String sql;    sql = "SELECT HR_EmpCode,HR_EmpName FROM dbo.HR_Employee WHERE HR_EmpCode ='001002'";    ResultSet rs = stmt.executeQuery(sql);    //STEP 5: Extract data from result set    while(rs.next()){       //Retrieve by column name       //int id  = rs.getInt("id");       //int age = rs.getInt("age");       String HR_EmpCode = rs.getString("HR_EmpCode");       String HR_EmpName = rs.getString("HR_EmpName");       //Display values       //System.out.print("ID: " + id);       //System.out.print(", Age: " + age);       System.out.println(" HR_EmpCode: " + HR_EmpCode);       System.out.println(", HR_EmpName: " + HR_EmpName);    }    //STEP 6: Clean-up environment    rs.close();    stmt.close();    conn.close(); }catch(SQLException se){    //Handle errors for JDBC    se.printStackTrace(); }catch(Exception e){    //Handle errors for Class.forName    e.printStackTrace(); }finally{    //finally block used to close resources    try{       if(stmt!=null)          stmt.close();    }catch(SQLException se2){    }// nothing we can do    try{       if(conn!=null)          conn.close();    }catch(SQLException se){       se.printStackTrace();    }//end finally try }//end try}//end main}//end 


0 0
原创粉丝点击