如何使用变量[duplicate]从Java的mysql表中检索值

问题描述 投票:1回答:1
我正在使用CLI中使用MySQL和Java的学生注册和登录系统。我想通过输入用户名从数据库表中检索数据。相关用户名的数据应在所需位置进入CLI。这是我编写的代码

package lab; import java.sql.*; import java.util.Scanner; public class Student_Login { String uname, pwd; public void input(){ System.out.println("Student Login Form\nUsername: "); Scanner sc = new Scanner(System.in); uname = sc.next(); System.out.println("Password: "); pwd = sc.next(); } public void retrieve(){ try{ Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydatabase", "root", "Luxan@22" ); Statement st = con.createStatement(); ResultSet result = st.executeQuery("select * from emp where Username = "+uname); result.next(); String Name = result.getString(2); System.out.println("Hi "+Name+"You have successfully registered for the following courses"); ResultSet rs = st.executeQuery("select * from course where username ="+ uname); result.next(); String course = rs.getString(2); System.out.println(course); con.close(); }catch(Exception e) {System.out.println(e);} } public void choice() { System.out.println("Please select an option\n1.Exit\n2.Registration"); Scanner sc = new Scanner(System.in); int select = sc.nextInt(); switch(select) { case 1: System.out.println("Bye"); break; case 2: Student_Registration SR = new Student_Registration(); SR.input(); SR.add(); SR.Display(); break; } } }

但是在运行代码时,将出现如下异常。我输入了已经存储在表中的用户名luxan:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'luxan' in 'where clause'

java mysql jdbc
1个回答
1
投票
使用准备好的语句:

String sql = "SELECT * FROM emp WHERE Username = ?"; PreparedStatement st = con.prepareStatement(sql); st.setString(1, uname); ResultSet rs = st.executeQuery(); if (rs.next()) { String Name = result.getString(2); }

我没有努力重构整个代码,但是准备好的语句背后的基本思想是,变量参数仅由?占位符表示,我们将Java的值绑定到该占位符。
© www.soinside.com 2019 - 2024. All rights reserved.