在JDBC中使用变量

时间:2016-05-02 23:25:00

标签: java mysql jdbc

我想要使用driverID的用户输入,如果用户输入id,则将onJob更改为true。

因此,例如,如果用户输入1作为驱动程序ID,则ID为1的驱动程序将onJob变量更改为1.

这是我目前的代码;

public class TaxiDriver {

    //String driverLocation = DRIVERFIRSTLOCATION;
    //String destinationintoAPI;

    //JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/DRIVER";

    //Database credentials

    static final String USER = "user";
    static final String PASS = "password";
    String driverId;
    static Scanner reader = new Scanner(System.in);

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            //STEP 2: Register JDBC driver
            Class.forName("com.mysql.jdbc.Driver");

            //STEP 3: Open a connection
            System.out.println("Connecting to a selected database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Connected database successfully...");

            System.out.println("Assign a driver to a jo...");
            reader.nextInt();

            //STEP 4: Execute a query
            System.out.println("Creating statement...");
            stmt = conn.createStatement();
            String sql = "UPDATE Drivers " +
                "SET OnJob = 1 WHERE id = (driverId)";
            stmt.executeUpdate(sql);

            // Now you can extract all the records
            // to see the updated records
            sql = "SELECT id, license, first, last, OnJob, Email, Telephone, Address, Postcode, Veichle  FROM Drivers";
            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next()) {
                //retrieve by column name

                int id = rs.getInt("id");
                int license = rs.getInt("license");
                String first = rs.getString("first");
                String last = rs.getString("last");
                int OnJob = rs.getInt("OnJob");
                String Email = rs.getString("Email");
                String Telephone = rs.getString("Telephone");
                String Address = rs.getString("Address");
                String Postcode = rs.getString("Postcode");
                String Veichle = rs.getString("Veichle");
                //Display
                System.out.print("ID: " + id);
                System.out.print(", license: " + license);
                System.out.print(", First: " + first);
                System.out.print(", Last: " + last);
                System.out.print(", Email; " + Email);
                System.out.print(", Telephone; " + Telephone);
                System.out.print(", Address; " + Address);
                System.out.print(", Postcode; " + Postcode);
                System.out.print(", Veichle;" + Veichle);
                if (OnJob == 0) {
                    System.out.println(": Driver is aviliable for pickup");
                } else {
                    System.out.println(": Driver is not aviliable for pickup");
                }
            }
            rs.close();
        } catch (SQLException se) {
            //Handle errors for JDBC
            se.printStackTrace();
        } catch (Exception e) {
            //Handle errors for Class.forName
            e.printStackTrace();
        } finally {
            //finally block used to close resources
            try {
                if (stmt != null)
                    conn.close();
            } catch (SQLException se) {
            }// do nothing
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }//end finally try
        }//end try
        System.out.println("Goodbye!");
    }//end main
}//end JDBCExample

现在我收到这些错误。

Connecting to a selected database...
Tue May 03 00:18:28 BST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. 
According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. 
For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. 
You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Connected database successfully...
Assign a driver to a jo...
2
Creating statement...
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'driverId' in 'where clause'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
    at com.mysql.jdbc.Util.getInstance(Util.java:387)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547)
    at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1541)
    at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2605)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1469)
    at TaxiDriver.main(TaxiDriver.java:71)
Goodbye!

提前非常感谢。

2 个答案:

答案 0 :(得分:4)

首先,您实际上需要在某处读取值driverId

除此之外,问题在于您的SQL语句。你有:

String sql = "UPDATE Drivers " +
             "SET OnJob = 1 WHERE id = (driverId)";

您告诉数据库查找记录“id”列的值等于其driverId列值的记录。

您需要将driverId变量的值放入SQL中,而不是将实际字符“driverId”放入SQL中,其中(如您所见)它被解释为列的名称。 / p>

使用您需要的方法:

String sql = "UPDATE drivers SET OnJob=1 WHERE id=" + driverId;

但动态SQL很危险,最好使用PreparedStatement。这将消除用户输入并防止SQL注入攻击。

String sql = "UPDATE drivers SET OnJob=1 WHERE id=?";
PreparedStatement ps = connection.createPreparedStatement(sql);
ps.setInt(1, Integer.parseInt(driverId));
ResultSet rs = ps.executeQuery();

答案 1 :(得分:0)

您似乎没有从用户输入设置driverId。 在执行脚本之前,使用有效的id值更新sql语句。

int driverId = 123;// This is user input, am assuming its type int.
String sql = "UPDATE Drivers SET OnJob = 1 WHERE id =" + driverId;
//now execute your sql

String driverId = "123";//This is user input, am assuming its type String.
String sql = "UPDATE Drivers SET OnJob = 1 WHERE id =" + "'" + driverId  + "'";
//now execute your sql

编辑:我强烈推荐QuantumMechanic使用PreparedStatement作为更安全的解决方案,并隐藏所有不同类型的处理。