如何使用java在ms访问中插入值

时间:2022-09-28 15:42:35
try 
{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con1=DriverManager.getConnection("jdbc:odbc:MyDatabase");
    st1=con1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    System.out.println("Connect database in BallMoves1.java .......");
    /*the below line giving error*/
    rs1 = st1.executeQuery("insert into highscore" + " (score) " + "values('"+score+"')");
    System.out.println("Score is inserted..");
    System.out.println("Score......."+score);
}catch(Exception e){ e.printStackTrace();}

/*highscore is table and attributes of table are (sid,score).

the resulting error is:

由此产生的错误是:

Connect database in BallMoves1.java .......
java.sql.SQLException: No ResultSet was produced
    at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(JdbcOdbcStatement.java:258)
    at BallMoves1.move(BallMoves1.java:378)
    at BallMoves1.run(BallMoves1.java:223)
    at java.lang.Thread.run(Thread.java:744)*/

1 个解决方案

#1


2  

You're calling executeQuery on something that isn't a query. But instead of calling execute with the same SQL, you should use a PreparedStatement:

您正在对不是查询的东西调用executeQuery。但是,与其使用相同的SQL调用execute,不如使用PreparedStatement:

String sql = "insert into highscore (score) values (?)";
try (Connection conn = DriverManager.getConnection("jdbc:odbc:MyDatabase");
    PreparedStatement statement = conn.prepareStatement(sql)) {
  statement.setInt(1, score);
  statement.executeUpdate();
  conn.commit();
}

Always use parameterized SQL, instead of plugging the values directly into the SQL - that protects you from SQL injection attacks, conversion errors, and hard-to-read code.

始终使用参数化SQL,而不是直接将值插入到SQL中——这将保护您不受SQL注入攻击、转换错误和难以读取的代码的影响。

Use a try-with-resources statement (as I have) to automatically close the statement and connection at the end of the block.

使用try-with-resources语句(正如我所做的)自动关闭块末尾的语句和连接。

#1


2  

You're calling executeQuery on something that isn't a query. But instead of calling execute with the same SQL, you should use a PreparedStatement:

您正在对不是查询的东西调用executeQuery。但是,与其使用相同的SQL调用execute,不如使用PreparedStatement:

String sql = "insert into highscore (score) values (?)";
try (Connection conn = DriverManager.getConnection("jdbc:odbc:MyDatabase");
    PreparedStatement statement = conn.prepareStatement(sql)) {
  statement.setInt(1, score);
  statement.executeUpdate();
  conn.commit();
}

Always use parameterized SQL, instead of plugging the values directly into the SQL - that protects you from SQL injection attacks, conversion errors, and hard-to-read code.

始终使用参数化SQL,而不是直接将值插入到SQL中——这将保护您不受SQL注入攻击、转换错误和难以读取的代码的影响。

Use a try-with-resources statement (as I have) to automatically close the statement and connection at the end of the block.

使用try-with-resources语句(正如我所做的)自动关闭块末尾的语句和连接。