所以我对 java 和 SQL 非常陌生,它们是我的第一个编程语言。我正在尝试使用 JDBC 做一些工作。我想允许用户输入 id 并根据变量返回查询。如果有人至少能指出我正确的方向......这是我开始的代码。请注意,它很粗糙,但只是想获得一段工作代码,以便我可以更好地在我的主类中实现它。
Scanner input = new Scanner(System.in);
Class.forName("org.sqlite.JDBC");
Connection conn =
DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Derek\\Documents\\Databases\\example.sqlite");
Statement stat = conn.createStatement();
PreparedStatement prep1 = conn.prepareStatement(
"insert into MedType values (?, ?);");
PreparedStatement prep2 = conn.prepareStatement(
"insert into Media values (?, ?,?, ?,?, ?);");
System.out.print("Please choose a database(MedType or Media): ");
String db=input.next();
if(db.equalsIgnoreCase("MedType"))
{
System.out.print("Enter in ID: ");
String answer1 = input.next();
System.out.print("");
String answer2 = input.nextLine();
System.out.print("Enter in Description: ");
String answer3 = input.nextLine();
prep1.setString(1, answer1);//add values into cell
prep1.setString(2, answer3);
prep1.addBatch();//add the columns that have been entered
}
conn.setAutoCommit(false);
prep1.executeBatch();
prep2.executeBatch();
conn.setAutoCommit(true);
System.out.print("Please Enter Query(One or All): ");
String q=input.next();
ResultSet rs= stat.executeQuery("select * from MedType;");
if(q.equalsIgnoreCase("all")){
while (rs.next()) {
System.out.print("All ID = " + rs.getString("ID") + " ");
System.out.println("All Description = " + rs.getString("Description"));}
}
if(q.equalsIgnoreCase("one")){
System.out.print("Enter ID: ");
}
int idNum=input.nextInt();
ResultSet oneRs = stat.executeQuery("select * from MedType Where"+ (rs.getString("ID")+"="+idNum));
if(q.equalsIgnoreCase("one")){
while (oneRs.next()) {
System.out.print("ID = " + oneRs.getString("ID") + " ");
System.out.println("Description = " + oneRs.getString("Description"));
}
}
rs.close();
oneRs.close();
conn.close();
}
}
ResultSet oneRs = stat.executeQuery("select * from MedType Where"+
(rs.getString("ID")+"="+idNum));
这就是我遇到麻烦的地方。创建一条语句,表示如果表的 id 等于用户输入,则从表中返回某些内容。我收到此错误
线程“main”java.sql.SQLException中出现异常:[SQLITE_ERROR] SQL错误或丢失数据库(靠近“=”:语法错误)
最佳答案
在查询中,您尝试通过传递 id 来访问单行。在一般的 sql 查询中,我们使用通过传递一些信息来访问单行。 select * from MedType where id=3 此查询将返回包含 id 等于 3 的行的结果集。 因此,在您的代码中,如果您的数据库 id 列是 int,则您的查询应该是 select * from MedType where id="+idNum+" 。 并仅将此查询保留在 if block 中,即
if(q.equalsIgnoreCase("one"))
{
System.out.print("Enter ID: ");
int idNum=input.nextInt();
ResultSet oneRs = stat.executeQuery("select * from MedType Where id="+idNum+" ");
// if id column in db is int if it is string then use id='"+idNum+"'
while (oneRs.next())
{
System.out.print("ID = " + oneRs.getString("ID") + " ");
System.out.println("Description = " + oneRs.getString("Description"));
}
}
关于java - 如何使用用户输入作为查询参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16354495/