当前位置:Gxlcms > 数据库问题 > Java连接SqlServer2008数据库(转)

Java连接SqlServer2008数据库(转)

时间:2021-07-01 10:21:17 帮助过:2人阅读

java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Test { public static void main(String args[]) { // Create a variable for the connection string. String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=AdventureWorks;integratedSecurity=true;"; String url = "jdbc:sqlserver://127.0.0.1:1368;databaseName=mydb;user=sa;password=qiaoning";//sa身份连接 String url2 = "jdbc:sqlserver://127.0.0.1:1368;databaseName=mydb;integratedSecurity=true;";//windows集成模式连接 // Declare the JDBC objects. Connection con = null; Statement stmt = null; ResultSet rs = null; try { // Establish the connection. System.out.println("begin."); Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con = DriverManager.getConnection(url); System.out.println("end."); // Create and execute an SQL statement that returns some data. String SQL = "SELECT TOP 10 * FROM aud_t_basis"; 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) { } } } }

 

 第二种:混合身份验证模式,用上边java代码的url2.

在集成模式下需要如下操作:

找到你刚才的解压目录:进入sqljdbc_3.0\chs\auth\x64,我的是64位系统,如果是32位就x86,将一个名为sqljdbc_auth.dll的文件拷贝到:C:\Windows\System32下,就好了

最后就是sqlserver2008用的是动态端口,需要你配置一下:

打开配置工具->SQLServer配置管理器->SQLServer网络配置->MSSQLSERVER的协议->TCP/IP启用,把TCP动态端口中的0都删掉,留空;然后把列表拉到最下边(IPALL),配置一个固定端口,以后你连接数据库就用这个端口就可以了:如下图


技术分享
 这里我用的是1368,数据库重启后,就可以用上面的程序连接了.

 

  • 查看图片附件

Java连接SqlServer2008数据库(转)

标签:

人气教程排行