首页 > 编程 > Java > 正文

JAVA与数据库连接方法(二)

2019-11-17 06:33:44
字体:
来源:转载
供稿:网友

    现在介绍第二种方法,用关厂商提供的相应驱动程序来连接。

    这种实现方法是直接使用数据库厂商提供的用专用的网络协议创建的驱动程序,通过它可以直接将JDBC API调用转换为直接网络调用。这种调用方式一般性能比较好,而且也是实用中最简单的方法。因为它步需要安装其他的库或中间件。几乎所有的数据库厂商都为他们的数据库提供了这种数据库提供了这种JDBC驱动程序,也可以从第三方厂商获得这些驱动程序。

    从网址http://industry.java.sun.com/PRodUCts/jdbc/drivers/可以看到所有有用的驱动程序的清单。其结果如图所示:

    应用程序---JDBC API---驱动程序---数据源

    这里首先要安装JDBC的驱动程序,推荐SP2版本的,可从微软网站上下载
    http://www.microsoft.com/downloads/details.aspx?FamilyID=9f1874b6-f8e1-4bd6-947c-0fc5bf05bf71&DisplayLang=en 下载最下面的SETUP.EXE

    这个驱动程序要配合SQL SERVER2000 SP3A,相应下载URL为
    http://www.microsoft.com/china/sql/downloads/sp3.asp 下载 chs_sql2ksp3.exe

    假如用JAVA SDK直接编译运行的话需要设置环境变量,将安装好的JDBC驱动里面的LIB三个文件设置为环境变量:
    classpath: 
    D:/program  files/Microsoft  SQL  Server/jdbc/lib/msbase.jar;
    D:/program  files/Microsoft  SQL  Server/jdbc/lib/MSSQLserver.jar;
    D:/program  files/Microsoft  SQL  Server/jdbc/lib/msutil.jar;

    安装即可用微软的驱动程序连接数据库了,相应代码与前面基本相同:

import java.sql.*;
import java.io.*;
public class DBColumn {

 public static void main(String[] args) {
  Connection con=null;
  Statement sm=null;
  String command=null;
  ResultSet rs=null;
  String tableName=null;
  String cName=null;
  String result=null;
  BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
  try
  {
   Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
   System.out.println("驱动程序已加载");
   //SQL SERVER的登陆方式必须为使用SQL SERVER密码登陆认证方式
   con=DriverManager.getConnection("jdbc:microsoft:sqlserver://SERVERNAME:1433","USER","PASSWord"); 
   con.setCatalog("GoodsSupply");
   System.out.println("OK,成功连接到数据库");
  }catch(Exception ex) {
   ex.printStackTrace();
  }
  try
  {
   sm=con.createStatement();
   System.out.println("输入表名");
   tableName=input.readLine();


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表