JDBC UPDATE ERROR with MySQL - error code 1054 - java

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".

Related

Why SAVE button is not saving to MySQL database in Java code

What's wrong with the code, no errors but still it's not saving to database, where did it go wrong?
Even if the database is created, the code won't store the values
JButton btnSave = new JButton("SAVE");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Get Breed and age entered by user
String breed = textBreed.getText();
String breed_age = textAge.getText();
// Convert age into integer
int age = Integer.parseInt(breed_age);
// Connection
try {
//open connection
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/animal_db", "root", "root");
// Insert data into table
Statement stm = con.createStatement();
String dog_table = "CREATE TABLE IF NOT EXISTS breedtest" +
"(id INT NOT NULL AUTO_INCREMENT," +
"breed VARCHAR(30)," +
"age INT," +
"PRIMARY KEY (id))";
stm.executeUpdate(dog_table);
String sql = "INSERT INTO breedtest VALUES ('"+textBreed.getText()+"', "+textAge.getText()+")";
// Execute Statement
stm.executeUpdate(sql);
// display message of record inserted
JOptionPane.showMessageDialog(btnSave, "Record added");
textBreed.setText("");
textAge.setText("");
//Close connection
con.close();
}catch(Exception E) {
}
}
});
textBreed & textAge are text field from the GUI
here is a creen shot of the GUI.
enter image description here
I have amended the following lines, and it works fine
// Insert data into table
Statement stm = con.createStatement();
String dog_table = "CREATE TABLE IF NOT EXISTS breedtest" +
"(id INT NOT NULL AUTO_INCREMENT," +
"breed VARCHAR(30)," +
"age INT," +
"PRIMARY KEY (id))";
stm.executeUpdate(dog_table);
String sql = "INSERT INTO breedtest" + "(breed, age)" + "VALUES(?, ?)";
PreparedStatement brd = con.prepareStatement(sql);
brd.setString(1, textBreed.getText());
brd.setString(2, textAge.getText());
brd.execute();
data got captured in database with the confirmation message.
Displayed message
Database table
This line of code is not executing
String sql = "INSERT INTO breedtest" + "(breed, age)" + "VALUES ("+textBreed.getText()+", "+textAge.getText()+")";
but this one is.
String sql = "INSERT INTO breedtest" + "(breed, age)" + "VALUES(?, ?)";
I understand that in my first code I omitted to name the columns, thanks for flagging this.
Could someone explain me which line of code is associating the "VALUES(?, ?)" to the textfield.
You need to modify your Insert query with the following
String sql = "INSERT INTO breedtest(breed, age) VALUES ('"+textBreed.getText()+"', "+textAge.getText()+")";

How to Delete rows in table using Variable in SQL

How should I delete a row using a java variable in SQL table?
I am trying to delete a record from table member (with two columns, name and year) using what the user has input (variable newName and newYear). I want to find the row that has the same record as what the user has input (name = newName && year=newYear) and delete it. However, this code doesn't change anything on the table (no row is deleted although what I have input is correct). What's wrong with my code?
String newName = memName.getText();
int newYear = parseInt(memYear.getText());
are the variables used in the code below.
try {
s = c.createStatement();
t = "DELETE FROM member " +
"WHERE (name='" + newName + "'&& year='" + newYear + "')";
s.executeUpdate(t);
s.close();
c.commit();
c.close();
} catch (SQLException ex) {
Logger.getLogger(AddMember.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(null, "Saved.");
memName.setText(null);
memYear.setText(null);
I want the row with the info the user input to be deleted from the table, but it didn't make any changes to my table.
the problem you have is that in SQL you cannot use && instead use AND as shown in the following code:
t = "DELETE FROM member " +
"WHERE (name='" + newName + "' AND year='" + newYear + "')";

MySQL Java syntax error

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

more efficient way to inset values into a mysql table

I have a Collection and I want to write Nodes' values into a mysql table. Right now I connect to the database, create a statement and then for each Node in the collection I run
// open the connection then
Statement statement = connect.createStatement();
for (Node n : vertices) {
statement.execute("INSERT INTO " + table + " (name, department) values ('" + n.getName() + "', '" + n.getOrgId() + "')");
}
// then I close the connection
I am wondering if is there a more efficient method to deal with such a task.
Use prepared statements:
String query = "insert into " + table + " (name, department) values (?,?)";
try(PreparedStatement ps = connection.prepareStatement(query)) {
for(Node n : vertices) {
ps.setString(1, n.getName());
ps.setInt(2, n.getOrgId());
ps.addBatch();
}
ps.executeBatch();
} catch(SQLException e) {
// Exception handling
}
Notice that because of the way your query is built it is still vulnerable to SQL injection attacs (because you are building the string with a variable table). I recommend you either remove the table variable or take measures to ensure that that variable is never visible by any user of your program.
Try to prepare the query for a multiple insert, then execute it at once:
String query = "INSERT INTO " + table + " (name, department) values";
for (Node n : vertices) {
query += " ('" + n.getName() + "', '" + n.getOrgId() + "')");
}
statement.execute(query);
You can insert multiple rows at the same time.
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
Check this Link

How to add blocks of text with punctuations in PostgreSQL

I am using java to execute postgresql statements. In one step, I need to create a table in which one column will store blocks of text (that may contain punctuation marks, such as comma, semi-colon, etc).
What data type do I use to populate this column?
For example, in the given example, I am creating a table called "MYTHOUGHTS", and that has a column called "THOUGHTS". I am trying the following code:
try {
con = DriverManager.getConnection(url, user, password);
System.out.println("Opened Database Successfully");
st = con.createStatement();
String sql = "CREATE TABLE MYTHOUGHTS " + "(ID INT PRIMARY KEY NOT NULL," + " THOUGHTS TEXT NOT NULL," + " Number INT NOT NULL," + " ADDRESS CHAR(50), " + " SALARY REAL)";
st.executeUpdate(sql);
sql = "INSERT INTO COMPANY (ID,THOUGHTS,AGE,ADDRESS,SALARY) " + "VALUES (1," + "This is life, as I see it. Do you think otherwise?" + ", 32, 'California', 20000.00 );";
st.executeUpdate(sql);
st.close();
con.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
I get the following error:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "life"
Position: 68
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2161)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1890)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:560)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:403)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:331)
at com.vivek.PostgreSQLExample.main(PostgreSQLExample.java:39)
org.postgresql.util.PSQLException: ERROR: syntax error at or near "life"
Position: 68
It is possible that TEXT data type is not appropriate. Please, let me know how I may add multiple lines of text that may have commas and periods into a column.
Thank you for your time and assistance. Highly appreciate it.
Use the text data type. The contents do not matter, the only thing you can't put in text is the null byte \0.
If you're having problems with the contents then you're running dangerous code that's doing direct string interpolation, instead of using parameterized statements. See: http://bobby-tables.com/ , http://en.wikipedia.org/wiki/SQL_injection, http://docs.oracle.com/javase/tutorial/jdbc/basics/

Categories

Resources