如何在java中将数据插入数据库?

时间:2016-01-02 09:32:21

标签: java jdbc

我试图将一些数据插入我的数据库。但它给我一个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");
    }
}

1 个答案:

答案 0 :(得分:2)

你应该在insert语句中引用字符串。

所以你应该改变:

String query = "insert into customer values (null, "+fname+", "+lname+", "+tel+", "+email+", "+password+")";

String query = "insert into customer values (null, '"+fname+"', '"+lname+"', '"+tel+"', '"+email+"', '"+password+"')";

更合适的解决方案是在查询字符串中插入占位符,准备查询,并在execute方法中传递变量的值。这样,当这些字符串包含单引号(例如O'Connor)时,您将避免出现问题。更重要的是,通过这种方式,您可以避免SQL Injection Attacks