sqlserver数据如下;
TestSQL.java;
java
import java.sql.*;
public class TestSQL {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; //加载JDBC驱动
String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=test1"; //连接服务器和数据库
String user = "rabbit";
String pwd = "rabbit";
Connection dbConn;
Class.forName(driverName);
System.out.println("数据库驱动程序注册成功");
dbConn = DriverManager.getConnection(dbURL,user, pwd);
Statement stmt = dbConn.createStatement();
ResultSet rs = stmt.executeQuery("select id,name,salary from salary1");
while(rs.next()){//如果对象中有数据,就会循环打印出来
System.out.println(rs.getInt("id")+","+rs.getString("name")+","+rs.getInt("salary"));
}
rs.close();
dbConn.close();
}
}
编译;jar包和源代码在同一目录;java执行的时候指定classpath;
出现下图错误;
看一下目录下有2个sqljdbc的jar包;
删掉一个,保留带4的这个;然后执行,输出数据如下;