String connectionUrl = "jdbc:sqlserver://192.168.0.247:1433;"
+ "databaseName=northwind;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Properties pro = new Properties();
pro.setProperty("user", "sa");//设置用户名
pro.setProperty("password", "sa");//设置密码
File file = new File(
"C://Program Files//Microsoft SQL Server JDBC Driver 3.0//sqljdbc_3.0//chs//sqljdbc.jar");
URL url = file.toURL();
URLClassLoader loader = new URLClassLoader(new URL[] { url },
ClassLoader.getSystemClassLoader());
java.sql.Driver driver = (java.sql.Driver) loader.loadClass(
"com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
driver.connect(connectionUrl, pro);//需要使用java.sql.Driver.connect链接
JOptionPane.showMessageDialog(null, "数据库连接成功!");
}
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) {
}
}
}