一开始eclipse连接sql server 2008数据库是对的,代码如下,然后在此基础上修改就出错了。
import java.sql.*;
public class Main {
public static void main(String [] args)
{
String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL="jdbc:sqlserver://localhost:1433;DatabaseName=Student";//Student填数据库的名字
String userName="sa";
String userPwd="123";
try
{
Class.forName(driverName);
System.out.println("加载驱动成功!");
}catch(Exception e){
e.printStackTrace();
System.out.println("加载驱动失败!");
}
try{
Connection dbConn=DriverManager.getConnection
(dbURL,userName,userPwd);
System.out.println("连接数据库成功!");
}catch(Exception e)
{
e.printStackTrace();
System.out.print("SQL Server连接失败!");
}
}
}
修改后的代码是
import java.sql.*;
public class Main {
static Statement sql;
static ResultSet res;
static Connection con;
public Connection getConnection(){
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("加载驱动成功!");
}catch(Exception e){
e.printStackTrace();
System.out.println("加载驱动失败!");
}
try{
con=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=Class","sa","123");
System.out.println("连接数据库成功!");
}catch(Exception e)
{
e.printStackTrace();
System.out.print("SQL Server连接失败!");
}
return con;
}
public static void main(String [] args)
{
Main m=new Main();
try{
sql=con.createStatement();
res=sql.executeQuery("select * from B班");
while(res.next()){
String id=res.getString("Id");
String name=res.getString("Name");
int grade=res.getInt("Grade");
System.out.print("编号"+id);
System.out.print("姓名"+name);
System.out.print("成绩"+grade);
}}catch(Exception e){
e.printStackTrace();
}
}
}
系统提示出错:
java.lang.NullPointerException
at Main.main(Main.java:29)