gpt4 book ai didi

java - 如何使用java在ms access中插入值

转载 作者:搜寻专家 更新时间:2023-10-30 23:08:21 24 4
gpt4 key购买 nike

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).

产生的错误是:

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)*/

最佳答案

您正在对非查询的内容调用 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();
}

始终使用参数化 SQL,而不是将值直接插入 SQL - 这样可以保护您免受 SQL 注入(inject)攻击、转换错误和难以阅读的代码。

使用 try-with-resources 语句(就像我一样)自动关闭 block 末尾的语句和连接。

关于java - 如何使用java在ms access中插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23361577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com