java 如何在SQL语句中使用变量[重复]

eyh26e7m  于 2023-04-19  发布在  Java
关注(0)|答案(1)|浏览(154)

此问题已在此处有答案

java sql insert(4个答案)
关闭2天前.

import java.sql.*;

public class insert {
    
    public static void main(String[] args) throws SQLException {
        
        String url =  "jdbc:mysql://127.0.0.1:3306/datenbank";
        String user = "root";
        String password = "123456";
        
        Connection conn = null;
        Statement stmt = null;
        
        try {
            
            conn = DriverManager.getConnection(url,user,password);
            
            stmt = conn.createStatement();
            
            String sql = "INSERT INTO bestenliste "
                    + "(SpielerName)"
                    + Login.nameWeiss;   //this is the varialbe i want to insert into the column SpielerName

            stmt.execute(sql);
            
            System.out.println("Insert Complete");
            
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(stmt != null) {
                stmt.close();
            }if(conn != null) {
                conn.close();
            }
        }
    }
}

SQL语法中有错误;检查与您的MySQL服务器版本对应的手册,以在第1行的'Login.nameWeiss)'附近使用正确的语法

kxeu7u2r

kxeu7u2r1#

缺少“values()”。请尝试:

String sql = "INSERT INTO bestenliste "
                + "(SpielerName)"
                + “ values (‘“ + Login.nameWeiss + “‘)”;

此外,查询应该参数化。上面的版本效率低下,容易受到sql注入的影响。尝试:

String sql = "INSERT INTO bestenliste "
                + "(SpielerName)"
                + “values (?)”;

PreparedStatement createPlayer = conn.prepareStatement(sql);

createPlayer.setString(1, Login.nameWeiss);
createPlayer.executeUpdate();

相关问题