我正在尝试插入我在文本字段中键入的值,并且一旦触发了actionListener,它就会插入到数据库(Microsoft SQL)中。
但是每当我尝试插入时,它都不会插入值,但也没有任何编译错误。我知道这个问题已被问过很多次,但到目前为止我找不到解决问题的方法。
EDITED
编辑:我从使用createStatement更改为PreparedStatement但我不确定这是否是编写preparedStatement的正确方法
按下JButton时会触发此方法。
public void createAccount()
{
String idValue = idField.getText();
String pwValue = pwField.getText();
int idValueInt = Integer.parseInt(idValue);
String insertVal = "INSERT INTO Students" +"(StudentID,StudentPW) VALUES"+"
(?,?)";
PreparedStatement prep = null;
try{
prep = conn.prepareStatement(insertVal);
prep.setInt(1, idValueInt);
prep.setString(2, pwValue);
prep.executeUpdate();
System.out.println("Record Added");
}
catch(SQLException e){
System.out.println(e.getMessage());
}
}
连接到主
中调用的数据库
public void StartConnection(){
try {
static final String DB_URL =
"jdbc:sqlserver://localhost:1433;databaseName=Java;
integratedSecurity=true;";
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (stmt != null) {
conn.close();
}
} catch (SQLException se) {
}// do nothing
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
}