【问题标题】:How to retrieve values from a mysql table in java using variables [duplicate]如何使用变量从java中的mysql表中检索值[重复]
【发布时间】:2020-03-18 11:35:14
【问题描述】:

我正在使用 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'

【问题讨论】:

  • 同意,但 OP 真正应该做的是使用带参数的查询,where Username = ?"
  • @RiggsFolly 那个副本不正确。

标签: java mysql jdbc


【解决方案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);
}

我没有努力重构您的整个代码,但prepared statements 背后的基本思想是变量参数仅由? 占位符表示,我们将Java 中的值绑定到该占位符。

【讨论】:

  • 为什么不投票关闭它作为重复呢?
  • @Joakim 如果你愿意,你可以投票关闭。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多