Java code for inserting data into a MySQL database gives an 'Error: No value specified for parameter 2' – how do I fix it?

huangapple go评论52阅读模式
英文:

Java code for inserting data into a MySQL database gives an 'Error: No value specified for parameter 2' - how do I fix it?

问题

我正在为国际文凭(IB)计算机科学的内部评估工作,我有一段代码,基本上是要在一个包含科目名称和该科目下的事件数量的科目表中插入一行数据。

它可以通过引用数据库中的另一个名为“Events”的单独表来查看事件的数量,并将该科目的名称插入其中的事件数量。

然而,我遇到的错误是:

> 错误:未为参数2指定值

发生了什么问题,我该如何解决?

以下是要使用的代码:

private void insertSubject_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    String command = evt.getActionCommand();

    String dbName = "ScheduleManagementDB";
    String tableName = "Subjects";
    String[] columnNames =
    {
        "Subject", "EventAmount"
    };
    String dbQuery = "INSERT INTO Subjects VALUES(?,?)";

    JavaMySQL_DB objDb = new JavaMySQL_DB(dbName);
    Connection myDbConn = objDb.getDbConn();
    PreparedStatement ps = null;
    try
    {
        ps = myDbConn.prepareStatement(dbQuery);
    }
    catch (SQLException ex)
    {
        System.out.print("error");
    }
    String Subject;
    int EventAmount;

    Subject = insertSubject_Field.getText();

    String getCountQuery = "SELECT COUNT(*) FROM Events WHERE SubjectE = ?";
    int count = 0;

    try
    {
        ps.setString(1, Subject);
        ps.executeUpdate();

        PreparedStatement getCountPs = myDbConn.prepareStatement(getCountQuery);
        getCountPs.setString(1, Subject);
        ResultSet rs = getCountPs.executeQuery();
        if (rs.next())
        {
            count = rs.getInt(1);
        }

        ps.setInt(2, count);
        ps.executeUpdate();

        System.out.println("Data Inserted");
    }
    catch (SQLException e)
    {
        System.out.println("Error: " + e.getMessage());
    }
}

我尝试不使用结果集,因为我认为getCountQuery语句仍然会工作,因为我只需要一个值,但那也不起作用。

英文:

I'm working on my internal assessment for IB for computer science, and I have the snippet of code that basically is supposed to insert a row within a subjects table that contains both a subject name, and the amount of events under such subject.

It is able to see the amount of events by referencing another separate table called 'Events' within the database, and will put in the amount of events that will have the name of the subject inserted within.

However, the error I am getting is:

> Error: No value specified for parameter 2

What is going on and how do I fix this?

Here's the code to work with:

private void insertSubject_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String command = evt.getActionCommand();
String dbName = "ScheduleManagementDB";
String tableName = "Subjects";
String[] columnNames =
{
"Subject", "EventAmount"
};
String dbQuery = "INSERT INTO Subjects VALUES(?,?)";
JavaMySQL_DB objDb = new JavaMySQL_DB(dbName);
Connection myDbConn = objDb.getDbConn();
PreparedStatement ps = null;
try
{
ps = myDbConn.prepareStatement(dbQuery);
}
catch (SQLException ex)
{
System.out.print("error");
}
String Subject;
int EventAmount;
Subject = insertSubject_Field.getText();
String getCountQuery = "SELECT COUNT(*) FROM Events WHERE SubjectE = ?";
int count = 0;
try
{
ps.setString(1, Subject);
ps.executeUpdate();
PreparedStatement getCountPs = myDbConn.prepareStatement(getCountQuery);
getCountPs.setString(1, Subject);
ResultSet rs = getCountPs.executeQuery();
if (rs.next())
{
count = rs.getInt(1);
}
ps.setInt(2, count);
ps.executeUpdate();
System.out.println("Data Inserted");
}
catch (SQLException e)
{
System.out.println("Error: " + e.getMessage());
}

I tried not using a result set either as I thought that the getCountQuery statement would work anyway, as I just need a value, but that didn't work either.

答案1

得分: 2

直到*绑定* **两个** 参数之前您无法调用 `PreparedStatement` `ps`。您当前只绑定了第一个参数然后尝试调用执行更新然后尝试通过调用另一个 `PreparedStatement` 加载第二个值首先执行这个操作另外您当前泄漏了您的 `Connection`、`Statement``ResultSet`。要么自己关闭它们要么使用 `try-with-Resources`。类似于

	private void insertSubject_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
		String command = evt.getActionCommand();
		String dbName = "ScheduleManagementDB";
		String tableName = "Subjects";
		String[] columnNames = { "Subject", "EventAmount" };
		String dbQuery = "INSERT INTO Subjects VALUES(?,?)";
		String getCountQuery = "SELECT COUNT(*) FROM Events WHERE SubjectE = ?";

		JavaMySQL_DB objDb = new JavaMySQL_DB(dbName);

		String Subject = insertSubject_Field.getText();
		int count = 0;
		try (Connection myDbConn = objDb.getDbConn()) {
			try (PreparedStatement getCountPs = myDbConn
						.prepareStatement(getCountQuery)) {
				getCountPs.setString(1, Subject);
				try (ResultSet rs = getCountPs.executeQuery()) {
					if (rs.next()) {
						count = rs.getInt(1);
					}
				}
			}
			try (PreparedStatement ps = myDbConn.prepareStatement(dbQuery)) {
				ps.setString(1, Subject);
				ps.setInt(2, count);
				ps.executeUpdate();
				System.out.println("数据已插入");
			} catch (SQLException e) {
				System.out.println("错误: " + e.getMessage());
			}
		}
	}
英文:

You can't invoke the PreparedStatement ps until you bind both parameters. You currently bind the first one, then attempt to call execute update and then attempt to load the second value by calling another PreparedStatement. Perform that first. Also, you currently leak your Connection, Statement(s) and ResultSet(s). Either close them yourself, or use a try-with-Resources. Something like

private void insertSubject_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
String command = evt.getActionCommand();
String dbName = "ScheduleManagementDB";
String tableName = "Subjects";
String[] columnNames = { "Subject", "EventAmount" };
String dbQuery = "INSERT INTO Subjects VALUES(?,?)";
String getCountQuery = "SELECT COUNT(*) FROM Events WHERE SubjectE = ?";
JavaMySQL_DB objDb = new JavaMySQL_DB(dbName);
String Subject = insertSubject_Field.getText();
int count = 0;
try (Connection myDbConn = objDb.getDbConn()) {
try (PreparedStatement getCountPs = myDbConn
.prepareStatement(getCountQuery)) {
getCountPs.setString(1, Subject);
try (ResultSet rs = getCountPs.executeQuery()) {
if (rs.next()) {
count = rs.getInt(1);
}
}
}
try (PreparedStatement ps = myDbConn.prepareStatement(dbQuery)) {
ps.setString(1, Subject);
ps.setInt(2, count);
ps.executeUpdate();
System.out.println("Data Inserted");
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

huangapple
  • 本文由 发表于 2023年6月5日 10:15:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403172.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定