怎么用java连接sqlserver数据库
2个回答
展开全部
导入SqlServer JDBC的驱动,
SQLServer的JDBC URL=
jdbc:sqlserver://172.30.202.21:1433;DatabaseName=AirAutoMonitor
3. 获得连接的代码
public static Connection getConnection(String url, String username, String password)
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的数据库连接的通用方法。
展开全部
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) {
}
}
}
}
谢谢采纳。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询