2013-01-12 68 views
-1

我可以得到一個java mysql數據庫連接的示例並在按鈕單擊事件中插入記錄嗎?這是我在jframe中使用的代碼,但它不起作用,它有一個錯誤。java在按鈕單擊事件中插入記錄到數據庫

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()); 
     } 

回答

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(); 
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()); 
    } 
} 
+0

什麼ü意思?請你可以編輯上面的代碼.. – user1966589

+0

@ user1966589看到更新。 –

+0

我在連接con = createConnection();時得到語法錯誤; – user1966589

相關問題