MySQL Java syntax error - java

Trying to figure out what the error is in this java code.
The SQLException reads: " 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 'order (item_quantity, customer_id, product_id) VALUES (5, 191, 31)'
The order table looks like
order_id int pk ai <br>
item_quantity <br>
customer_id int <br>
product_id int <br>
And the function that inserts is:
public void createOrder(int productQuantity, int customerId, int productId) throws SQLException {
sql = "INSERT INTO order (item_quantity, customer_id, product_id) VALUES (" + productQuantity + ", " + customerId + ", " + productId + ")";
try {
int a = stmt.executeUpdate(sql);
if (a == 1) {
System.out.println("Order Added");
} else {
System.out.println("Order Failed");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
Any help would be greatly appreciated, can't seem to figure this out.

Enclose the order (table name) by backtick
like below:
INSERT INTO `order` (item_quantity, customer_id, product_id) VALUES...
Note:
The backticks help you from accidentally using a name that is a reserved word in SQL for example. Take a table named "where", it's a stupid name for a table I agree, but if you wrap it in backticks it will work fine

Related

cannot set null to a unique column

so this is my table
CREATE TABLE "client" (
"id" INTEGER,
"name" TEXT COLLATE NOCASE,
"surname" TEXT COLLATE NOCASE,
"number" TEXT UNIQUE COLLATE NOCASE,
"car_brand" TEXT,
"modele" TEXT,
"phone_nbr" TEXT,
PRIMARY KEY("id" AUTOINCREMENT));
when im adding a new statment from my java application i can add only one time NULL to the column number but i can add many nulls from the db browser
this is the code that i use
String number = tf_number.getText();
if(tf_number.getText().trim().isEmpty())
number = null;
String name = tf_name.getText();
String surname = tf_surname.getText();
String phoneNbr = tf_phoneNbr.getText();
String car_brand = tf_brand.getText();
String modele = tf_modele.getText();
Client c = new Client(name, surname, number, car_brand, modele, phoneNbr);
ClientCRUD pcd = new ClientCRUD();
pcd.addClient(p);
and this is the sql error
[SQLITE_CONSTRAINT_UNIQUE] A UNIQUE constraint failed (UNIQUE constraint failed: client.number)
this is the addClient() fonction
public void addClient(Client t) {
try {
String requete = "INSERT INTO CLIENT(name,surname,number,car_brand,MODELE,phone_nbr)"
+ "VALUES ('"+t.getClientName()+"','"+t.getClientSurname()+"','"+t.getNumber()+"',"
+ "'"+t.getCarBrand()+"','"+t.getModele()+"','"+t.getPhone()+"')";
Statement st = MyConnection.getInstance().getCnx()
.createStatement();
st.executeUpdate(requete);
System.out.println("Client added");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
any solution ?
public void save(Person person) {
String query = "INSERT INTO person_info (" +
" name_p, " +
" age, " +
" address, " +
" email " +
")" +
"VALUES(?, ?, ?, ?)";
try(Connection connection = dbConnection.getConnection()) {
PreparedStatement prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, person.getName());
prepStatement.setInt(2, person.getAge());
prepStatement.setString(3, person.getAddress());
prepStatement.setString(4, null);
prepStatement.execute();
}
catch (SQLException e){
e.printStackTrace();
}
}
##This will solve your problem
You code inserts the string "null" and not a real null like your browser do.
So there can be only 1 string with value "null" in that unique column.
You can use preparedStatement with parameters instead of the statement you use.
E.g:
PreparedStatement preparedStatement = connection.prepareStatement(sql))
This answers how to insert null using prepared statement: Insert null using prepared statement
And your sql string for the query should have the parameters.
See more about prepared statements: Prepared Statements Tutorial

org.postgresql.util.PSQLException: ERROR: syntax error at or near "7"

I'm trying to create private chats in my app, but when I try to create the table I get this error:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "7"
Position: 14
Code:
public static String checkIfChatExists(String code, String friend) throws SQLException {
String i = LoginManager.checkCode(code);
if(i.equals("code-not-exists")) {
return "invalid-code";
}
ResultSet rs = conn.prepareStatement("SELECT * FROM pwchats").executeQuery();
while (rs.next()) {
if(rs.getString("user1").equals(i) && rs.getString("user2").equals(friend) || rs.getString("user1").equals(friend) && rs.getString("user2").equals(i)) {
return "exists";
}
}
PreparedStatement pre = conn.prepareStatement("INSERT INTO pwchats(user1, user2) VALUES(?, ?)");
pre.setString(1, i);
pre.setString(2, friend);
pre.execute();
PreparedStatement getChatId = conn.prepareStatement("SELECT * FROM pwchats WHERE user1 = ? AND user2 = ?;");
getChatId.setString(1, i);
getChatId.setString(2, friend);
ResultSet rss = getChatId.executeQuery();
while (rss.next()) {
PreparedStatement chat = conn.prepareStatement("CREATE TABLE " + rss.getInt("id") + "chat (username text NOT NULL, created_at timestamp with time zone NOT NULL DEFAULT now(), avatar text NOT NULL, message text NOT NULL, id serial NOT NULL);");
chat.execute(); //ERROR
return "done";
}
return "wat";
}
The error that you are seeing likely comes from there:
preparedStatement chat = conn.prepareStatement("CREATE TABLE " + rss.getInt("id") + "chat (...);");
Usually in SQL, a table name cannot begin with a number. Postgres would still allow that if you were to surround the table name with double quotes, but then you would need to double quote the table name everytime your query it, which could be tedious.
One solution would to put the number at the end of the table name, like:
preparedStatement chat = conn.prepareStatement("CREATE TABLE chat" + rss.getInt("id") + " (...);");
Demo on DB Fiddle:
create table 7chat(x int);
ERROR: syntax error at or near "7"
LINE 1: create table 7chat(x int);
^
create table "7chat"(x int);
-- works
create table chat7(x int);
--works

you have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' ' in Line 1

I tried to insert following data to the database. but it gives me the above
this error.
you have an error in your SQL syntax; check the manual that corresponds to
your MariaDB server version for the right syntax to use near ' ' in Line 1.
i tried several things but it is not fixing.
try{
Statement stat = Database.getStatement();
stat.executeUpdate("INSERT INTO"+" admission"+
" (a_id,sickness,recPhysicianDetails,
admittedDate,Patient_ID,Doctor_id,Doctor_id1)"+"
VALUES
('"+txt1.getText()+"',
'"+txt7.getText()+"','"+txt8.getText()+"', '"+txt6.getText()+"',
( SELECT ID FROM patient WHERE Patient_name='"+txt3.getText()+"' ),
( SELECT ID FROM employee WHERE Name='"+txt9.getText()+"' ),
( SELECT ID FROM employee WHERE Name='"+txt10.getText()+"')" );
}
catch(Exception e){
e.printStackTrace();
}
In your solution, quotation marks (') are not rightly placed, plus there is a missing closing bracket in the end. Using PreparedStatement will make sure you don't need to worry about quotation marks, try this:
Connection conn = //get connection
PreparedStatement stat = conn.prepareStatement("INSERT INTO admission (a_id,sickness,recPhysicianDetails,admittedDate,Patient_ID,Doctor_id,Doctor_id1)"
+" VALUES(?, ?, ?, ?, (SELECT ID FROM patient WHERE Patient_name = ?),(SELECT ID FROM employee WHERE Name = ?),(SELECT ID FROM employee WHERE Name = ?))");
stat.setString(1, txt1.getText());
stat.setString(2, txt7.getText());
stat.setString(3, txt8.getText());
stat.setString(4, txt6.getText());
stat.setString(5, txt3.getText());
stat.setString(6, txt9.getText());
stat.setString(7, txt10.getText());
stat.executeUpdate();
I will suggest to use prepared statement instead directly calling the value from the textbox.
try{
Statement stat = Database.getStatement();
stat.executeUpdate("INSERT INTO admission"+
"(a_id,sickness,recPhysicianDetails,admittedDate,Patient_ID,Doctor_id,Doctor_id1)"+
" VALUES('"+txt1.getText()+"','"+txt7.getText()+"','"+txt8.getText()+"','"+txt6.getText()+"',"+
"(SELECT ID FROM patient WHERE Patient_name='"+txt3.getText()+"'),"+
"(SELECT ID FROM employee WHERE Name='"+txt9.getText()+"'),"+
"(SELECT ID FROM employee WHERE Name='"+txt10.getText()+"')");
}
catch(Exception e){
e.printStackTrace();
}
You here inserted some double quotation marks in wrong places, please check it, it should work.

Trying to find if an item exists in database table, if it doesn' t exist. add it

I am trying to develop a program where you want to add a new book ( title, author, date,...)
but i do not want to add the author multiple times..
i want the program to check if the author already exists in the table, if not it will add him... here is my code :
public void insert_bk(String m, String a, String b, String c, String d, String e) {
String sql="Select * from author where Full_Name='"+b+"'";
System.out.println(sql);
try {
opencn();
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
while (rs.next()) {
String id=rs.getString("Author_ID");
System.out.println(id);
st.executeUpdate("INSERT into book (`Book_ID`,`Title`,`Author_ID`,`Date_of_release`,`Theme`,`Edition`)"+ "VALUES ('" + m+ "','" + a+ "','" + id+ "', '" + d+ "', '" + e+ "', '" + c+ "')");
}
}
catch(SQLException exp) {
System.out.println(exp.getMessage());
}
}
In this code it just checks if the Author exists and adds the book... how can i make the condition that if the author does not exist it will add him along with the book?
Any ideas?
Thank you in advance :)
Instead of using a while-loop you should put rs.next() into an if-statement. If the call returns false no author is present and it has to be inserted.
you can do this stored procedure
declare #i int
Select #i=count(*) from author where Full_Name=#FullName
IF(#i < 1)
BEGIN
// INSERT
END
This might help
String query = "Select * from author where Full_Name='"+b+"'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader rdr;
con.Open();
cmd.ExecuteNonQuery();
rdr = cmd.ExecuteReader();
if (rdr.Read()) { // if you have an author
//do your updation code here
}
else {
//if rdr.Read() gives 0 which will be the case when our
//author wont exist past the code for adding an author here
}
You can make a conditional insert by adding the keyword IGNORE into the statement. Depending on which SQL database you are using the answer is slightly different. I'll demonstrate here the two ways for MySQL and sqlite, but of course there are more.
For MySQL
INSERT IGNORE INTO authors VALUES(?,?...,?)
For SQLite
INSERT OR IGNORE INTO authors VALUES(?,?,...,?);

JDBC UPDATE ERROR with MySQL - error code 1054

this is the code
PreparedStatement res1 = null;
String insertUser = "INSERT INTO users (uid,firstname,lastname,score) VALUES (" +
this.getFbUid() + "," +
this.getFbFirstName() + "," +
this.getFbLastName() + ",0)";
System.out.println(insertUser);
try
{
res1 = connection.prepareStatement(insertUser);
res1.executeUpdate();
System.out.println("executed query to db with the message" + res1);
}
catch(SQLException e)
{
System.out.println("setUserInDb: " +e.getMessage());
System.out.println("error num: " +e.getErrorCode());
}`
I'm getting error code 1054:
Unknown column 'Alon' in 'field list' when trying to insert the line "INSERT INTO users (uid,firstname,lastname,score) VALUES (123456,Alon,xyz,0)
In the db I have table users with varchar columns uid, firstname, lastname, and score.
What am I doing wrong?
Alon seems or type varchar should be under '
Use Prepared statement rather
Just as Jigar pointed it out,
When u insert String values into the table you should use the values inside single or double quote(' or ").
Eg 'Hello',"Hello".

Categories

Resources