与数据库的Java连接
我已用尽一切办法来解决这个问题,但没有结果。我已经安装了“SQLManagementStudio 2012”,并创建了一个虚拟数据库和方法,但仍然得到一个“空点异常指针”。Java和JDBC在用户变量下设置 以下是屏幕截图和代码与数据库的Java连接,java,sql,Java,Sql,我已用尽一切办法来解决这个问题,但没有结果。我已经安装了“SQLManagementStudio 2012”,并创建了一个虚拟数据库和方法,但仍然得到一个“空点异常指针”。Java和JDBC在用户变量下设置 以下是屏幕截图和代码 Static { // standard code to open a connection and statement to SQL Server database try { // Create a varia
Static {
// standard code to open a connection and statement to SQL Server database
try {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://SQL-SERVER;"
+ "databaseName=ItunesDB;integratedSecurity=true;";
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
} // Handle any errors that may have occurred.
catch (SQLException sqle) {
System.out.println("Sql Exception :" + sqle.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found Exception :" + e.getMessage());
}
}
public static String listAll() {
String output = "";
try {
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable");
while (res.next()) { // there is a result
// the name field is the thrid one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
output += res.getString(1) + " " + res.getString(2) + " - "
+ res.getString(3) + " " + res.getString(4) + " "
+ res.getString(5) + "\n";
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return output;
}
public static String getName(String key) {
try {
SELECT * FROM LibraryTable WHERE key = '04'
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable WHERE ID = '" + key + "'");
if (res.next()) { // there is a result
// the name field is the second one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
return res.getString(2);
} else {
return null;
}
} catch (Exception e) {
System.out.println(e);
return null;
}`enter code here`
数据库信息:
Dummy Database
ID Name Artist Quantity Price Rating Playcount
我需要做什么来修复此问题?以混合模式重新安装sql server。然后转到SQL Server配置管理器,检查是否启用了TCP/Ip。如果没有,请启用它并重新启动服务。然后在项目中添加SQLJDBCJAR。然后试试这个代码
Connection con = null;
try {
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;"
+ "user=sa;password=HerongYang;"
+ "database=AdventureWorksLT");
}
用户始终是sa,因为它是系统管理员您在哪里得到空指针异常??NPE在哪里?堆栈跟踪会很有帮助。当我的程序中的另一个类尝试检查跟踪列表时。很明显,在我的库类中添加SQL代码之前,该类工作正常。非常感谢。我将按照您的说明进行操作,并返回反馈。