本程序需要建立一个ODBC,名为“Northwind”的系统DSN,连接到SQL Server的Northwind数据库,
并查询Employees表中所有员工的姓名,程序如下:
package db2mssql;
import java.sql.*;
public class Main
{
public static void main(String args[])
{
Connection con;
Statement sql; //声明Statement对象
ResultSet rs;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e)
{
System.out.println(""+e);
}
try
{
con=DriverManager.getConnection("jdbc:odbc:Northwind","sa","sa");
sql=con.createStatement();
rs=sql.executeQuery("Select FirstName, LastName FROM Employees");
int i=0;
while(rs.next())
{
String FirstName=rs.getString(1); //获得数据库第一列
String LastName=rs.getString(2);
System.out.println("Name" + i++ +": "+ FirstName + " " + LastName); //输出信息
}
con.close();
}
catch(SQLException el){}
}
}