2016-11-23 19 views
-2

我編寫了一個簡單的java代碼來接受表單中的參數並將其存儲在表中。下面是代碼:提交表單後獲取MySQL語法錯誤

String fname = request.getParameter("username"); 
String mail = request.getParameter("email"); 
String country = request.getParameter("country"); 
String pword = request.getParameter("password"); 

Class.forName("com.mysql.jdbc.Driver"); 
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/foodforthought", "root", 
     "********");            
Statement statement = connection.createStatement(); 
try { 
    int i = statement.executeUpdate("insert into users (username,email,country,password) values ("+fname+"','"+mail+"','"+country+"','"+pword+")"); 
    out.println("Successfully registered"); 
} catch (Exception e) { 
    out.println(e); 
    e.printStackTrace(); 
} 

Error:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'India',')' at line 1 

國家的值是India其從表格的到來。我該如何解決它?

+3

您在第一個圓括號後面和最後一個'values'零件之前缺少引號。更好地使用'PreparedStatement'來避免這個問題和可能的注入。 – Berger

+0

''「+ pword +」'你最後錯過了一個單引號。 – Jagrati

+0

int i = statement.executeUpdate(「insert into users(username,email,country,password)values(''+ fname +'',''+ mail +'','」+ country +'','「+ pword +」 '););' – ettanany

回答

3

您的單引號是錯誤的。

但從來沒有使用從形式readed值插入到你的數據庫,你可能會遭受SQL注入

http://www.w3schools.com/Sql/sql_injection.asp

使用製得,其中的參數被正確解析到特定類型的報表

一個例子:

String query = "insert into dept(deptnum, deptname, deptloc) values(?, ?, ?)"; 
    PreparedStatement pstmt = conn.prepareStatement(query); // create a statement 
    pstmt.setInt(1, 1); // set input parameter 1 
    pstmt.setString(2, "deptname"); // set input parameter 2 
    pstmt.setString(3, "deptLocation"); // set input parameter 3 
    pstmt.executeUpdate(); // execute insert statement 
1

你已經在你的曲遺忘'字符紅黴素:

("+fname+"','"+mail+"','"+country+"','"+pword+") 
^ here        and here^

將其更改爲('"+fname+"','"+mail+"','"+country+"','"+pword+"')

或者更好地利用PreparedStatement避免這種錯誤和SQL注入問題也是如此。

String sql = "insert into users (username, email, country, password) values (?, ?, ?, ?)"; 
PreparedStatement preparedStatement = connection.prepareStatement(sql); 

// Insert values safe and indirectly to avoid mistakes and SQL injection 
preparedStatement.setString(1, fname); 
preparedStatement.setString(2, mail); 
preparedStatement.setString(3, country); 
preparedStatement.setString(4, pword); 

// Perform the update 
int count = preparedStatement.executeUpdate(); 
+0

ResultSet rs = preparedStatement.executeUpdate();'給出錯誤:'類型不匹配:無法從int轉換爲ResultSet' –

+0

對,我犯了一個錯誤。謝謝:) –

+0

你能糾正你的錯誤嗎? –