import java.sql.*;
import java.io.*;
public class User {
String s1;
int age;
String s2;
String s3;
/**
* @param args
* @return
*/
public void AddUser() throws SQLException {
try {
// TODO Auto-generated method stub
BufferedReader str = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter your name");
s1 = str.readLine();
System.out.println("Enter your age");
age = Integer.parseInt(str.readLine());
System.out.println("sex");
s2 = str.readLine();
System.out.println("DOB");
s3 = str.readLine();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:20june");
String query = "insert into UserDetails values(?,?,?,?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, s1);
ps.setInt(2, age);
ps.setString(4, s2);
ps.setString(3, s3);
ps.executeUpdate();
System.out.println("Record Inserted");
ps.close();
con.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
public void SearchUser() throws SQLException, IOException {
String str1;
try {
BufferedReader str2 = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter your search");
str1 = str2.readLine();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:20june");
String query1 = "SELECT * FROM UserDetails WHERE UserName like'str1%'";
PreparedStatement ps = con.prepareStatement(query1);
ps.setString(1, str1);
ps.executeUpdate();
ps.close();
con.close();
}
catch (NullPointerException e)
{
System.out.println(e);
} catch (Exception ex) {
System.out.println(ex);
}
}
public static void main(String[] args) throws IOException, SQLException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
User u1 = new User();
{
System.out.println("-------Menu-----------");
System.out.println("1.Add User Details ");
System.out.println("2.Search user");
System.out.println("Enter your choice");
int m = Integer.parseInt(br.readLine());
switch (m) {
case 1:
u1.AddUser();
break;
case 2:
u1.SearchUser();
break;
default:
System.out.println("Invalid choice");
break;
}
}
}
}
最佳答案
查看堆栈跟踪以查找导致NPE的行。然后确定哪个变量为null并修复代码。我们无法为您提供帮助,因为我们无法访问您的数据库,因此我们无法执行代码。
如果问题是您不知道是哪行导致了问题,请使用以下命令打印出堆栈跟踪:
e.getStackTrace();
当您赶上NPE时。
我对SQL不太了解,但是我使用如下代码指定参数:
String sql = "INSERT INTO Page (Name, Title) VALUES (?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, "Name1" );
stmt.setString( 2, "Title1" );
stmt.executeUpdate();
这样做的目的是使SQL保持简单,因此您不必担心定界符。
关于java - 搜索查询中的java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6435211/