今天我尝试了链接了数据:
/**
* @(#)JDBC.java
*
*
* @author
* @version 1.00 2011/8/24
*/
import java.sql.*;
public class JDBC {
public static void main(String[] args) {
// 声明JDBC驱动程序类型
String JDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
//定义JDBC驱动程序对象
String conURL = "jdbc:sqlserver://localhost;databaseName=mayi;user=sa;password=123";
Connection con = null;
PreparedStatement ps = null;
// Statement s=null;
ResultSet rs = null;
try {
///加载驱动
Class.forName(JDriver);
///链接数据库URL
con = DriverManager.getConnection(conURL);
///数据库操作
ps = con.prepareStatement("select * from users");
rs = ps.executeQuery();
while (rs.next()) {
System.out.println(" userId:" + rs.getInt(1) + " username:"
+ rs.getString(2) + " userPassword:" + rs.getString(3)
+ " email:" + rs.getString(4) + " grade:"
+ rs.getInt(5)+"\n");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
///关闭链接
try {
if(rs!=null){
rs.close();
rs=null;
}
if (ps != null) {
ps.close();
ps = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
编译运行,出现了这样的错误:Errors exist in required project 运行可以得到正确的数据!!
网上搜一下: 原因如下:
因为可能是同一个工程中的其他代码有错误,而执行的代码与这个有错误的代码没有关系,因为在同一个project,Eclipse依然会报错,但没有影响到执行的那段代码