gpt4 book ai didi

搜索查询中的 java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-02 08:16:01 24 4
gpt4 key购买 nike

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 的行。然后确定哪个变量为空并修复代码。我们无法帮助您,因为我们不能;我们无法执行代码,因为我们无权访问您的数据库。

如果问题是您不知道哪一行导致了问题,则使用以下方法打印堆栈跟踪:

e.getStackTrace();

当你 catch 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.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6435211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com