JDBC链接SQLServer数据库的大致步骤

我写大致步骤,每个步骤的具体做法,可以自行百度

1、        安装好SQLServer数据库、eclipse

2、        配置SQLServer的IP和端口号,这个可以上网搜,配置SQLServer为sa登录

3、        在SQLServer数据中创建yq数据库,在yq数据库中创建yq_user数据表,当然,名字可以自己起,在代码中注意改正就行

4、        下载安装JDBC驱动驱动


完成之后会出现一个文件夹,如下


5、        在Java中新建ConnetDB项目,项目中新建Test2类,导入上图中文件




只能导入一个,不然会出错

6、        Test2代码:

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

 

public class Test2

{

publicstatic void main(String[] args)

{

 

       //Create a variable for the connection string.

       StringconnectionUrl = "jdbc:sqlserver://localhost:1433;" +"databaseName=AdventureWorks;integratedSecurity=true;";

       Stringurl ="jdbc:sqlserver://192.168.1.140:1433;databaseName=yq;user=sa;password=123";//sa身份连接

 

       //Declare the JDBC objects.

       Connectioncon = null;

       Statementstmt = null;

       ResultSetrs = null;

 

       try

       {

             //Establish the connection.

             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

             con= DriverManager.getConnection(url);

 

             //Create and execute an SQL statement that returns some data.

             StringSQL = "SELECT TOP 10 * FROM yq_user";

             stmt= con.createStatement();

             rs= stmt.executeQuery(SQL);

 

             //Iterate through the data in the result set and display it.

             while(rs.next())

             {

                  System.out.println(rs.getString(4)+ " " + rs.getString(6));

             }

       }

 

       //Handle any errors that may have occurred.

       catch(Exception e)

       {

             e.printStackTrace();

       }

 

       finally

       {

             if(rs != null)

                  try

                  {

                        rs.close();

                  }catch (Exception e)

                  {

                  }

             if(stmt != null)

                  try

                  {

                        stmt.close();

                  }catch (Exception e)

                  {

                  }

             if(con != null)

                  try

                  {

                        con.close();

                  }catch (Exception e)

                  {

                  }

       }

}

}

 

链接方式有集成和使用sa身份链接,体现在使用的链接字符串中,这里使用的是sa链接,建议也使用,不然会很麻烦。

 

你可能感兴趣的:(sql,数据库,jdbc,server)