动态链接jdbc

来源:互联网 发布:网络创新设计大赛作品 编辑:程序博客网 时间:2024/05/16 06:33

  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) {
    }
  }
 }