java在按钮单击事件中将记录插入数据库

时间:2013-01-12 16:02:11

标签: java mysql database

我可以获取java mysql数据库连接的示例并在按钮单击事件中插入记录吗?这是我在jframe中使用的代码但它不起作用它有错误。

 private void btnlogActionPerformed(java.awt.event.ActionEvent evt) {                                       

     user=txtuser.getText();
      char[] pass=jPasswordField1.getPassword();
             String passString=new String(pass);
            try{                
                **Connection con =createConnection();**             


java.sql.PreparedStatement statement= con.prepareStatement ("INSERT INTO login(username,Password) VALUES ('" + user + "','" + passString + "')");

statement.setString(1,user);
    statement.setString(2,passString);
statement.execute();
            }
            catch(Exception e){
                JOptionPane.showMessageDialog(null,"Exception: "+ e.toString());
            }

public static void main(String args[]) {
 try {
            Class.forName("com.mysql.jdbc.Driver");
            String connectionUrl = "jdbc:mysql://localhost/Stock?"+
                                   "user=root&password=";
            Connection con = DriverManager.getConnection(connectionUrl);
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null,"SQL Exception: "+ e.toString());
        } catch (ClassNotFoundException cE) {
            JOptionPane.showMessageDialog(null,"Class Not Found Exception: "+ cE.toString());
        }

2 个答案:

答案 0 :(得分:0)

在声明参数时应使用parameter placeholder (?),不要连接变量。

String strQuery = "INSERT INTO login(username,Password) VALUES (?,?)";
java.sql.PreparedStatement statement = con.prepareStatement(strQuery);
statement.setString(1,user);
statement.setString(2,passString);

更新1

private void btnlogActionPerformed(java.awt.event.ActionEvent evt) 
{                                       
    user=txtuser.getText();
    char[] pass=jPasswordField1.getPassword();
    String passString=new String(pass);
    try
    {                
        Connection con = createConnection();          
        String strQuery = "INSERT INTO login(username,Password) VALUES (?,?)";
        java.sql.PreparedStatement statement = con.prepareStatement(strQuery);
        statement.setString(1,user);
        statement.setString(2,passString);
        statement.executeUpdate();
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(null,"Exception: "+ e.toString());
    }
}

答案 1 :(得分:0)

您的Connection变量的范围限定为try/catch块。您需要在块外移动声明并使用:

con = createConnection();

try/catch区块内。

使用PreparedStatement占位符(?)将构建正确的SQL字符串,并保护您免受SQL Injection攻击:

PreparedStatement statement = 
   con.prepareStatement ("INSERT INTO login(username, Password) VALUES (?, ?)");

另外,使用executeUpdate进行数据库写操作。取代

statement.execute();

statement.executeUpdate();