Access mysql database in eclipse using java

12,440

Solution 1

When inserting varchar text to MySQL tables, you need to surround it in single quotes like this:

String insert = "INSERT INTO customer(name,C_ID,address,email) VALUES ('a',5,'b','c');";

Solution 2

Access databases need ";" at the end of sql command.

String insert = "INSERT INTO customer(name,C_ID,address,email) VALUES ('a',5,'b','c');";

Edit: And you need to put text data into query like this

VALUES ('a',5,'b','c')

You may need to "escape" ' (quote) characters. I dont know how to do this in java, maybe like this:

VALUES (\'a\',5,\'b\',\'c\')
Share:
12,440
Grant
Author by

Grant

Student. Like to programming and just started Android programming. Still learning by my own and with your help. :)

Updated on June 14, 2022

Comments

  • Grant
    Grant almost 2 years

    I created a simple mysql database table using following query:

    CREATE TABLE customer(
    name varchar(20),
    C_ID int NOT NULL AUTO_INCREMENT,
    address  varchar(20),
    email varchar(20),
    PRIMARY KEY(C_ID)
    );
    

    Now I want to insert values to this table. My client like this:

    package com.orderdata.ws;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.PreparedStatement;
    
    import com.mysql.jdbc.Statement;
    
    public class OrderData {
    public static void main(String[] args)throws Exception{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/orderdata","root","chathura");
        Statement stmt = (Statement) con.createStatement();
        String insert = "INSERT INTO customer(name,C_ID,address,email)      VALUES (a,5,b,c)";
        stmt.executeUpdate(insert);
    
    }
    
    }
    

    But this gives an exception "Exception in thread "main" 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 '(a,5,b,c)' at line 1............"

    How can I insert data using eclipse???

  • Grant
    Grant about 12 years
    Still have the same problem "Exception in thread "main" 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 '(a,5,b,c)' at line 1 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Nativ‌​e M...