SQL in Prepared Statement throwing SQL exception - java

I'm trying to figure out why this code is throwing an SQL exception. When I run this code it prints "Bad SQL in customer insert ps", which is the message in that inner catch block. I've got multiple prepared statements with SQL inserts like this both in this class and also elsewhere in my application. They're all working fine. I've looked through this one over and over again, and I can't figure out why this one is throwing an exception.
try {
Connection conn = DBconnection.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT customerId FROM customer WHERE customerName=\"" + name + "\";");
System.out.println(ps.toString());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customerId = rs.getString("customerId");
}
try {
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement("INSERT "
+ "INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)"
+ "VALUES(\"" + name + "\", " + addressId + ", " + active + ", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\");");
customerInsert.executeUpdate();
System.out.println(customerInsert.toString());
System.out.println(rs.toString());
} catch (SQLException sq) {
System.out.println("Bad SQL in customer insert ps");
}
} catch (SQLException customerIdException) {
System.out.println("Bad SQL in customer ps");
}

You're using PreparedStatement as though you were using Statement. Don't put the parameters in the SQL, put in placeholder ? marks. Then use the various setXyz methods (setString, setInt, etc.) to fill in the parameters:
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement(
"INSERT INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)" +
"VALUES(?, ?, ?, ?, ?, ?, ?);"
);
customerInsert.setString(1, name);
customerInsert.setInt(2, addressId);
// ...etc. Notice that the parameter indexes start with 1 rather than 0 as you might expect

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

how to insert into mysql database with java

i want to insert inputs i take from user into mysql database the connection is right but the insertion gives me error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 ''u_fname',
'u_lname', 'u_uname', 'u_pass', 'u_age', 'u_adderess') values('20','o'
at line 1
My code is:
public void adduser(User s) {
try {
sql = "insert into users ('u_fname', 'u_lname', 'u_uname', 'u_pass', 'u_age', 'u_adderess')"
+ "values('" + s.getFirstname() + "','" + s.getLastname()
+ "','" + s.getUsername() + "','" + s.getPassword() + "','" + s.getAge() + "','" + s.getAdderss() + "')";
stmt = conn.createStatement();
int i = stmt.executeUpdate(sql);
if (i > 0) {
System.out.println("ROW INSERTED");
} else {
System.out.println("ROW NOT INSERTED");
}
} catch (Exception e) {
System.out.println(e);
}
}
To insert into mysql, follow these steps-
Create a Java Connection to our example MySQL database. I believe you already took care of it. It will be something like this-
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Create a SQL INSERT statement, using the Java PreparedStatement
syntax. Your PreparedStatement SQL statement will be as following this format-
String sql = " insert into users (first_name, last_name, date_created, is_admin, num_points)"
+ " values (?, ?, ?, ?, ?)";
Set the fields on our Java PreparedStatement object. It will done as-
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString (1, s.first_name);
preparedStmt.setString (2, s.last_name);
preparedStmt.setDate (3, s.date_created);
preparedStmt.setBoolean(4, s.is_admin);
preparedStmt.setInt (5, s.num_points);
Execute a Java PreparedStatement.
preparedStmt.execute();
Close our Java MYSQL database connection.
conn.close();
Catch any SQL exceptions that may come up during the process.
catch (Exception e)
{
System.err.println("Got an exception!");
// printStackTrace method
// prints line numbers + call stack
e.printStackTrace();
// Prints what exception has been thrown
System.out.println(e);
}

Insert int value of Resultset in SQL-Database

I'm working with a MySQL-Server and I'm trying to select an ID from another table and insert that ID in a table but it doesn't work all the time.
Code:
public void submit() throws Exception {
Connection connection = getConnection();
Statement stmt = connection.createStatement();
Statement stmt1 = connection.createStatement();
ResultSet asset_id = stmt.executeQuery("SELECT id FROM cars.asset_type WHERE asset_type.name =" + "'" + sellables.getValue()+ "'");
while (asset_id.next()) {
System.out.println(asset_id.getInt("id"));
}
double value = parseDouble(purchased.getText());
System.out.println(value);
LocalDate localDate = purchased_at.getValue();
String insert = "INSERT INTO asset (type_id, purchase_price, purchased_at) VALUES ('"+ asset_id + "','" + value +"','" + localDate +"')";
stmt1.executeUpdate(insert);
}
I keep getting the same error message.
Caused by: java.sql.SQLException: Incorrect integer value: 'com.mysql.cj.jdbc.result.ResultSetImpl#1779d92' for column 'type_id' at row 1
There's no value in doing two client/server roundtrips in your case, so use a single statement instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
If you really want to insert only the last ID from your SELECT query (as you were iterating the SELECT result and throwing away all the other IDs), then use this query instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
ORDER BY id DESC -- I guess? Specify your preferred ordering here
LIMIT 1
Or with the JDBC code around it:
try (PreparedStatement s = connection.prepareStatement(
"INSERT INTO asset (type_id, purchase_price, purchased_at) " +
"SELECT id, ?, ? " +
"FROM cars.asset_type " +
"WHERE asset_type.name = ?")) {
s.setDouble(1, parseDouble(purchased.getText()));
s.setDate(2, Date.valueOf(purchased_at.getValue()));
s.setString(3, sellables.getValue());
}
This is using a PreparedStatement, which will prevent SQL injection and syntax errors like the one you're getting. At this point, I really really recommend you read about these topics!

I need help selecting within a MySQL DateTime range in Java

I've got the following code in my app
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = " + userId +
" AND InsertTimestamp BETWEEN " + lastDate +
" AND " + DataProcessor.TODAY + " ORDER BY UserId, Occurred";
try{
if(null == conn)
openDatabaseConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery(); <------- this is the line which throws the SQL exception
retArray = this.getArrayListFromResultSet(rs);
}catch(SQLException sqle){
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
So when I run my app in the debugger, I get this exception message
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 '00:00:00.0 AND 2014-08-20 00:00:00.0 ORDER BY UserId, Occurred' at line 1
I'm reasonably certain that there's simple and reasonable solution to this, but I have not been able to find it.
I've tried looking in the MySQL manual for a solution or a different format.
I've tried running my timestamps through a TIMESTAMP() functino and a DATE() function in the SQL, neither of which helped.
I pulled the fully formed SQL out of the Java code and ran it in MySQL Workbench with no issues, what-so-ever. So now I'm looking to the experts for help.
Dates in SQL must be enclosed within single quotes like strings.
As you're using a prepared statemtent, why you don't use '?' and stmt.setDate(...)?
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = ?" +
" AND InsertTimestamp BETWEEN ?" +
" AND ? ORDER BY UserId, Occurred";
try {
if(null == conn) {
openDatabaseConnection();
}
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, userId);
stmt.setDate(2, lastDate);
stmt.setDate(3, DataProcessor.TODAY);
ResultSet rs = stmt.executeQuery();
retArray = this.getArrayListFromResultSet(rs);
} catch(SQLException sqle) {
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
Anyway, I think you are setting the dates in the opposite order. You should put first 'today' then lastDate. Although I don't know your constraints...

what's wrong with my insert statement? mysql java

what's wrong with my insert method?
my table has two columns, name, and artist..and timestamp, that too
actually, how do i pass timestamp argument to the insert statement?
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
/*FileWriter dir = new FileWriter(nameOfSong.getText()
+ ".txt");
BufferedWriter buffer = new BufferedWriter(dir);
buffer.write(nameOfSong.getText());
buffer.newLine();
buffer.write(artist.getText());
buffer.newLine();
buffer.newLine();
buffer.write(lyrics.getText());
buffer.close();
*/
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO lyrics1_lyrics1 VALUES(" +
nameOfSong.getText() + ", " + artist.getText() + "");
} catch (Exception z) {
System.err.println("Error: " + z.getMessage());
}
internalFrame.dispose();
}
});
)
Always use PreparedStatement.
String sql="INSERT INTO lyrics1_lyrics1 VALUES (?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1,nameOfSong.getText());
statement.setString(2,artist.getText());
statement.executeUpdate();
statement.close();
connection.close();
The text values need to be surrounded by single quotes ('').
And SQL-escaped to avoid SQL injection attacks, or the first time you have a song by Little Bobby Tables, all your DB are belong to him.
Better yet, use a PreparedStatement, and let the machine do work for you.
You can use prepared statement for it
String query = "INSERT INTO lyrics1_lyrics1(name, artist, timestamp) values(?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, name); // set input parameter 2
pstmt.setString(2, artist);
pstmt.setString(3, new TimeStamp(new Date().getTime()));
You need to add an import statement for the TimeStap;
import java.sql.Timestamp;
or else use
pstmt.setString(3, new java.sql.TimeStamp(new Date().getTime()));
Example: Prepared Statement Insert.
You can find a lot of example in java2s site.
Change the line to:
statement.executeUpdate("INSERT INTO lyrics1_lyrics1 VALUES('" +
nameOfSong.getText() + "', '" + artist.getText() + "'");
This might solve your problem:
statement.executeUpdate("INSERT INTO lyrics1_lyrics1 VALUES('" + nameOfSong.getText() + "', '" + artist.getText() + "')");`

Categories

Resources