2011-05-07 26 views
1

我想從用戶獲取數據(例如名稱),並使用JDBC其插入到MySQL。如何使用插入來自用戶考慮到MySQL數據庫的JDBC

我試圖做這樣的事情:

String uName = Username.getText(); (where uName is the name of the texfield) 

然後我想這個「UNAME」變量插入到MySQL。我知道這難道不工作,但我給它一個鏡頭,並試圖用下面的查詢做到這一點:

statement.executeUpdate("INSERT INTO users(username) VALUES(uName)"); 

(其中username是列名)

它沒有工作:)有什麼建議麼?

+0

建議您閱讀有關SQL注入和參數化的語句,如:https://www.owasp.org /index.php/Preventing_SQL_Injection_in_Java – 2011-05-07 10:45:14

回答

-1

假設您正在打開以正確的方式連接到你的數據庫,你可以這樣做:

String connString = "jdbc:mysql://localhost:3306/<db_name>?user=<user>&password=<password>"; 
Class.forName("com.mysql.jdbc.Driver"); 
Connection connect = DriverManager.getConnection(connString); 

// open connection 
// ... 

try 
{ 
    String query = "INSERT INTO users (username) VALUES (" + uName + ")" 
    statement = connect.createStatement(); 
    statement.executeUpdate(query); 
} 
catch (SQLException se) 
{ 
    es.printStackTrace(); 
} 
+0

感謝您的回覆!但是當我編譯你所寫的內容後,我得到了這個; com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:「字段列表」中的未知列'Koray',其中Koray是用戶在texfield(用戶名)中鍵入的內容。 – toruko 2011-05-07 18:23:35

+1

問題解決:我應該使用準備好的語句。我做了以下事情:PreparedStatement ps = connection.prepareStatement(「INSERT INTO Users(username)VALUES(?)」); ps.setString(1,username); ps.executeUpdate();它的工作。 – toruko 2011-05-07 19:44:45

相關問題