【问题标题】:jdbc Error, unable to connect to sqljdbc错误,无法连接sql
【发布时间】:2013-08-10 15:09:34
【问题描述】:

我想在我的项目中使用数据库,然后我使用此代码进行测试(来自 jdbc tutorialspoint) 并为我的代码和数据库更改它 然后我得到这个错误:

Creating statement...

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM test SET name=eee WHERE id=1' at line 1
Error: unable to connect to SQL!
java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM test SET name=eee WHERE id=1' at line 1
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1600)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1695)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3020)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:2949)
    at com.mysql.jdbc.Statement.execute(Statement.java:538)
    at Test.main(Test.java:49)

我的代码:

import java.sql.*;
import java.math.*;


public class Test {
    final static String DB_URL = "jdbc:mysql://localhost/testdb";
    final static String USER = "root";
    final static String PASS = "";

    final static String JDBC_DRIVER="com.mysql.jdbc.Driver";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(DB_URL,USER,PASS);
            System.out.println("Creating statement...");
            stmt = conn.createStatement();
            String sql = "UPDATE name FROM test SET name=eee WHERE id=1";


            Boolean ret = stmt.execute(sql);
            System.out.println("Return value is : " + ret.toString() );


            int rows = stmt.executeUpdate(sql);
            System.out.println("Rows impacted : " + rows );

            sql = "SELECT id,name FROM test";
            ResultSet rs = stmt.executeQuery(sql);

            while(rs.next()){
                int id  = rs.getInt("id");
                String name = rs.getString("name");

                System.out.print("ID: " + id);
                System.out.print(", name: " + name);
            }
            rs.close();
            stmt.close();
            conn.close();
        }
        catch(ClassNotFoundException ex) {
            ex.printStackTrace();
            System.out.println("\n" + ex.getMessage());
            System.out.println("Error: unable to load driver class!");

            System.exit(1);
        }
        catch(IllegalAccessException ex) {
            ex.printStackTrace();
            System.out.println("\n" + ex.getMessage());
            System.out.println("Error: access problem while loading!");
            System.exit(2);
        }
        catch(InstantiationException ex) {
            ex.printStackTrace();
            System.out.println("\n" + ex.getMessage());
            System.out.println("Error: unable to instantiate driver!");
            System.exit(3);
        }
        catch (SQLException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
            System.out.println("\n" + ex.getMessage());
            System.out.println("Error: unable to connect to SQL!");
            System.exit(4);
        }
    }
}

我的数据库是: Picture of my DB

我看到了这个page 但这对我没有帮助!

【问题讨论】:

  • 这是一个基本语法问题,您可以在 manual 中查找。

标签: java database jdbc


【解决方案1】:

起初您的声明不是有效的更新声明。它有约定:

update <tableName> set <column> = '<newValue>';

这是最简单的更新语句。它将更新所有行。然后您可以添加where clause 来选择行。检查this out

其次,您直接为列添加值,而不是将值包装到单引号中(它们必须被包装,否则它将不起作用)。要修复它,您需要添加单引号,例如:

set name = 'value';

当然,这可行,但我不喜欢这种方法。这是非常危险和不安全的。我建议您使用更安全(提防SQL injection)且更易于阅读的参数化语句。

PreparedStatement 用法的简单示例:

String sql = "UPDATE test SET name = ? WHERE id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, <nameValue>); // binding value for name column
ps.setInt(2, <idValue>); // binding value for where clause
ps.executeUpdate(); // executes statement

我想提一下 PreparedStatements 的几个主要优点:

  • 它们是预编译的、数据库端缓存的 SQL 语句线索 整体上更快的执行和重用相同 SQL 的能力 批量声明。
  • 通过内置转义自动防止 SQL 注入攻击 引号和其他特殊字符。
  • 简化 SQL 中非标准 Java 对象的设置(日期、时间、 时间戳、BigDecimal、Blob 等)

【讨论】:

  • 谢谢,我正在阅读 tuto,然后我使用该代码,但我认为您说的最好的代码,我在 php 中看到相同的代码,但我不知道这种语法对于java,那我一定要学,非常感谢
  • @asal 欢迎您。语法不难理解。您需要知道有占位符 (?) 将以相同的顺序替换为来自 PreparedStatement 类的 setXX() 方法的值。列的索引是从1开始的,可以看this tutorial
  • 我可以再问一个问题吗?代码中的第一个元素是什么?列数,例如 ps.setString(2,);在我的数据库中设置为第 2 列(表示名称)的属性?
  • 如果你有 where id = ? and name = ? 那么它将是 setInt(1, id)setString(2, name) 第一个 ? 在索引 1 处,第二个在索引 2 处等等。
  • 如果添加三个?,则需要设置三个值。
【解决方案2】:

这个查询不正确

String sql = "UPDATE name FROM test SET name=eee WHERE id=1";

修改为

String sql = "UPDATE test SET name='eee' WHERE id=1";

【讨论】:

  • :我之前测试过,但它有一个错误!但现在它的工作 =))) 非常感谢 mutch =))
  • 我不喜欢这种方法。它的意大利面条代码。它很危险,而且不太适合人类阅读。我不会对你投反对票,因为它有效,但这不是正确的做法。
  • @Sajmon 完全同意。正如 Sajmon 在他的回答中所建议的那样,您还应该考虑在未来的代码中使用preparedStatement。
  • 正如我在回答中提到的。
【解决方案3】:

String sql = "UPDATE name FROM test SET name=eee WHERE id=1"; 更改为

 String sql = "UPDATE test SET name='eee' WHERE id=1";

【讨论】:

    【解决方案4】:

    构造查询的另一个不错的选择是使用“Prepared statements” - 看看 oracle 教程 - link

    它有助于避免像在您的情况下出现的引号问题,并提供更大的顺序性。我记得它提供了一些准备工作,有助于更快地执行查询。

    【讨论】:

      【解决方案5】:

      替换:

       String sql = "UPDATE name FROM test SET name=eee WHERE id=1";
      

       String sql = "UPDATE name FROM test SET name='eee' WHERE id=1";
      

      【讨论】:

      • @all 这是一个正确的 SQL 查询吗?为什么要对错误答案投票
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      相关资源
      最近更新 更多