我创建了一个小程序,用户必须在其中将数据输入文本字段并从组合框中选择选项。我使用XAMPP创建了一个数据库,并通过Web浏览器为该程序创建了相应的表。
数据库称为activitydb,负责存储程序数据的表称为userdata。
表中的第一列称为UserID,它是一个整数,每次添加新条目时它都会自动递增。其余所有都是具有最大长度变化的varchar。
当前是程序的源代码:
Connection con = null;
Statement st = null;
try {
// activitydb = database name
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/activitydb?zeroDateTimeBehavior=convertToNull", "root", "");
st = con.createStatement();
// userdata = table name
String sqlconn = "INSERT INTO userdata (UserID, LastName, FirstName, MiddleName, Email, Sex, HomeAddress, City, CPUBrand, ComputerType, HardwareSpecs, GPUBrand, GPUType, GPUVRAM)";
PreparedStatement prdStmt = con.prepareStatement(sqlconn);
// Input of variable data into corresponding database table
// First table will be declared as null as it is an Integer designed with an Auto Increment
prdStmt.setString(1, null);
prdStmt.setString(2, jTextLastName.getText());
prdStmt.setString(3, jTextFirstName.getText());
prdStmt.setString(4, jTextMiddleName.getText());
prdStmt.setString(5, jTextEmail.getText());
prdStmt.setString(6, jComboBoxSex.getSelectedItem().toString());
prdStmt.setString(7, jTextHomeAddress.getText());
prdStmt.setString(8, jTextCity.getText());
prdStmt.setString(9, jComboBoxCPUBrand.getSelectedItem().toString());
prdStmt.setString(10, jComboBoxComputerType.getSelectedItem().toString());
prdStmt.setString(11, jComboBoxHardwareSpecs.getSelectedItem().toString());
prdStmt.setString(12, jComboBoxGPUBrand.getSelectedItem().toString());
prdStmt.setString(13, jComboBoxGPUType.getSelectedItem().toString());
prdStmt.setString(14, jComboBoxGPUVRAM.getSelectedItem().toString());
// Do this if something goes wrong
} catch (SQLException err) {
// Print error message to console for diagnosis
System.out.println(err.getMessage());
}
对于组合框,我使用getSelectedItem().toString()
将在内部找到的数据存储为字符串。
单击按钮将使该程序除了在控制台中执行以下操作外,什么也不做:Parameter index out of range (1 > number of parameters, which is 0).
您缺少占位符,您的查询应该是:
String sqlconn = "INSERT INTO userdata (UserID, LastName, FirstName, MiddleName," +
" Email, Sex, HomeAddress, City, CPUBrand, ComputerType, HardwareSpecs," +
" GPUBrand, GPUType, GPUVRAM) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";