java java中如何将数据插入到数据库中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34564438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert data into a database in java?
提问by Isuru Sandamal
I'm trying to insert some data into my database. But it get me an syntaxErrorException. Can anyone tell what is the wrong of this code.
我正在尝试将一些数据插入到我的数据库中。但它给我一个syntaxErrorException。谁能告诉我这段代码有什么问题。
import java.awt.HeadlessException;
import java.sql.*;
import javax.swing.*;
public class dbConnect {
//Connection conn=null;
public static Connection ConnectDB(){
String url = "jdbc:mysql://localhost:3306/db";
String username = "root";
String password = "";
System.out.println("Connecting database...");
try {
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
//connection.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
public static void insert(String s, String t, String u, String v, String w){
String fname, lname, tel, email, password;
fname=s;
lname=t;
tel=u;
email=v;
password=w;
Connection conn=ConnectDB();
try{
String query = "insert into customer values (null, "+fname+", "+lname+", "+tel+", "+email+", "+password+")";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
// execute the preparedstatement
preparedStmt.execute();
JOptionPane.showMessageDialog(null, "Data added");
}catch(SQLException | HeadlessException e){
JOptionPane.showMessageDialog(null, e);
}
}
public static void main(String args[]) {
//ConnectDB();
insert("isuru", "Sandamal", "0714521589", "isurusandamalisgmail.com", "1234");
}
}
回答by Renzo
You should quote string in the insert statement.
您应该在插入语句中引用字符串。
So you should change:
所以你应该改变:
String query = "insert into customer values (null, "+fname+", "+lname+", "+tel+", "+email+", "+password+")";
into
进入
String query = "insert into customer values (null, '"+fname+"', '"+lname+"', '"+tel+"', '"+email+"', '"+password+"')";
A more appropriate solution is to insert placeholder in the query string, prepare the query, and pass in the execute
method the values of the variables. In this way you will avoid problems when those string contains single quotes (e.g. O'Connor). And more important of all, in this way you can avoid SQL Injection Attacks.
更合适的解决方案是在查询字符串中插入占位符,准备查询,并在execute
方法中传递变量的值。这样,当这些字符串包含单引号(例如 O'Connor)时,您将避免出现问题。更重要的是,通过这种方式,您可以避免SQL 注入攻击。