怎么用java连接sqlserver数据库
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了怎么用java连接sqlserver数据库相关的知识,希望对你有一定的参考价值。
导入SqlServer JDBC的驱动,
SQLServer的JDBC URL=
jdbc:sqlserver://172.30.202.21:1433;DatabaseName=AirAutoMonitor
3. 获得连接的代码
throws ResourceDirectoryException
Connection conn = null;
String driverName = "";
Properties props = new Properties();
props.put("user", username);
props.put("password", password);
if (url != null || !"".equals(url))
if (url.indexOf("oracle") > -1)
databaseType = "oracle";
props.put("remarksReporting", "true");
driverName = "oracle.jdbc.driver.OracleDriver";
if (url.indexOf("sqlserver") > -1)
databaseType = "sqlserver";
driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
if (url.indexOf("mysql") > -1)
databaseType = "mysql";
driverName = "com.mysql.jdbc.Driver";
try
Class.forName(driverName);
conn = DriverManager.getConnection(url, props);
catch (ClassNotFoundException e)
throw new ResourceDirectoryException(e);
catch (SQLException e)
throw new ResourceDirectoryException(e);
return conn;
上面的代码是获得Oracle, MySQL, SqlServer的数据库连接的通用方法。
参考技术A import 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)
谢谢采纳。
asp用odbc连接sqlserver数据库代码怎么写
现在不能用oledb,oledb我会用。
第一个方法运行时提示Microsoft][ODBC SQL Server Driver][SQL Server]用户 '(null)' 登录失败。原因: 未与信任 SQL Server 连接相关联。
第二个方法Microsoft][ODBC 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序
则asp中,adodb对象连接可以使用"Provider=MSDASQL.1;Persist Security Info=False;Data Source=sql_test" 参考技术B <%
dim cnn
set cnn = server.createobject("adodb.connection")
cnn.connectionstring = "dsn = sqlserverdsn"
cnn.open
%>
以上是关于怎么用java连接sqlserver数据库的主要内容,如果未能解决你的问题,请参考以下文章