一般在管理工具里的数据源中建立数据源就可以对它进行连接了,比如我建立了一个Northwind的数据源,就可以连接他了,给你个示例程序:
import java.sql.*;public class DemoJDBC {
public static void main(String[] args) {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String source = "jdbc:odbc:Northwind";
try {
// 查找用于JDBC驱动的类,这种查找会使得Java虚拟机装入该类,这个类的静态初始化
// 语句块会对驱动程序进行初始化,从而下面可直接使用该驱动程序进行数据库连接,无需
// 再作其它额外的事情
Class.forName(driver);
} catch (ClassNotFoundException exc) {
// 当没有驱动程序时,应用程序无法继续运行,故退出程序
System.out.println("没有发现驱动程序:" + driver);
exc.printStackTrace();  System.exit(1);
}
try {
// 建立与指定数据库的连接
Connection connection = DriverManager.getConnection(source);
// 如果连接成功则检测是否有警告信息
SQLWarning warn = connection.getWarnings();
while (warn != null) {
System.out.println(warn.getMessage());
warn = warn.getNextWarning();
}
// 创建一个用于执行预编译SQL的语句对象
String sql = "SELECT ProductName FROM Products";
PreparedStatement pStm = connection.prepareStatement(sql);
// 发送和执行预编译的SQL语句,获得查询结果集
ResultSet result = pStm.executeQuery();
// 使用迭代模式访问查询结果集
while (result.next()) {
String name = result.getString("ProductName");
System.out.println(name);
}
// 关闭查询结果集
result.close();
// 关闭SQL预编译语句
pStm.close();
connection.close();
} catch (SQLException exc) {
System.out.println("在执行数据库访问时发生了错误!");
exc.printStackTrace();
}
}
}

解决方案 »

  1.   

    首先谢谢你!
    不过我编译的时候出现如下错误,你能帮我看一下,我的配置错在哪里吗?
    D:\myjava>javac DemoJDBC.java
    DemoJDBC.java:19: incompatible types
    found   : java.sql.Connection
    required: Connection
                            Connection connection = DriverManager.getConnection(source);
                                                                               ^
    DemoJDBC.java:21: cannot resolve symbol
    symbol  : method getWarnings ()
    location: class Connection
                            SQLWarning warn = connection.getWarnings();
                                                        ^
    DemoJDBC.java:28: cannot resolve symbol
    symbol  : method prepareStatement (java.lang.String)
    location: class Connection
                            PreparedStatement pStm = connection.prepareStatement(sql
    );
                                                               ^
    DemoJDBC.java:40: cannot resolve symbol
    symbol  : method close ()
    location: class Connection
                            connection.close();
                                      ^
    4 errors
      

  2.   

    import java.sql.*;
    还有要注意你那个url的格式要符合jdbc到sqlServer的标准哟