简体   繁体   English

准备好的语句失败

[英]Prepared Statement Failing

I'm using a prepared statment that should (using SQL & JDBC) insert data into a dataTable. 我正在使用准备好的语句,该语句应(使用SQL和JDBC)将数据插入到dataTable中。 I am using one that deletes data that works fine, but the insert one is not inserting any data into the data table and does not produce an error or warning. 我正在使用一种删除可以正常工作的数据的方法,但是插入一种方法是不在数据表中插入任何数据,并且不会产生错误或警告。 What could cause a prepared statement to fail in this way? 是什么导致准备好的语句以这种方式失败? Could inserting a null value into the prepared statement cause this? 可以在准备好的语句中插入null值吗?

What do you mean by "failing, but does not produce an error"? “失败,但不产生错误”是什么意思? How do you know it's failing then - is data not actually being inserted? 您怎么知道那是失败的-实际没有插入数据吗? Perhaps you're not committing a transaction? 也许您不提交交易?

Two ways to solve your problem. 解决问题的两种方法。

1st way: 第一种方式:

    Connection con = DriverManager.getConnection(DB_host, DB_UserName, DB_UserPassword);
    con.setAutoCommit(true);
String sql = "INSERT INTO Users (fName, lastName, userName, password) VALUES (?, ?, ?, ?)";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, "fName" );
stmt.setString(2, "lastName" );
stmt.setString(3, "userName" );
stmt.setString(4, "password" );
stmt.executeUpdate();

2nd way: 第二种方式:

Connection con = DriverManager.getConnection(DB_host, DB_UserName, DB_UserPassword);
String sql = "INSERT INTO Users (fName, lastName, userName, password) VALUES (?, ?, ?, ?)";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, "fName" );
stmt.setString(2, "lastName" );
stmt.setString(3, "userName" );
stmt.setString(4, "password" );
stmt.executeUpdate();
con.commit();

That is while creating connection object itself enable autocommit true for it. 那就是在创建连接对象本身的同时启用true的自动提交。 So tat it ll make the changes immediately reflect into ur database. 因此,它将使更改立即反映到您的数据库中。

Else after ur transaction make the connection as commit to ensure your transaction to be saved in database 在事务处理之后,否则将连接作为提交以确保您的事务被保存在数据库中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM