I have written this code to add stuff to the database, however, when I try running it it does not work, i've been looking for ways to do it, but i just cant seem to find the solution, can anyone help?
String mySQL ="INSERT INTO Measurement (Level, Time, Date, TankID)"+"VALUES (textField1, currentTime,currentDate,(SELECT TankID FROM Tanks WHERE TankName = '2' AND Site_ID = '1'))";
stmt.executeUpdate(mySQL);
Both your SQL and prepared statement are malformed. Try using an INSERT INTO ... SELECT here:
String sql = "INSERT INTO Measurement (Level, Time, Date, TankID) ";
sql += "SELECT ?, ?, ?, TankID ";
sql += "FROM Tanks ";
sql += "WHERE TankName = '2' AND Site_ID = '1'";
stmt.setString(1, textField1);
stmt.setString(2, currentTime); // not sure about the type here
stmt.setString(3, currentDate); // also not sure about the type
stmt.executeUpdate();
Note that I am unsure about both the Java and SQL binding types of the columns for currentTime and currentDate. If not string, then the above would have to change slightly.
You should be using PreparedStatement to properly set the first parameter of the insert query and check the documentation of your DB server to use existing functions to get current time and date.
For example, mySQL has functions CURDATE() and CURTIME()
String query = "INSERT INTO Measurement (Level, Time, Date, TankID) "
+ "VALUES (?, CURTIME(), CURDATE(), (SELECT TankID FROM Tanks WHERE TankName = '2' AND Site_ID = '1'))";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, textField1); // could be textField1.getText() or textField1.getValue()
statement.executeUpdate();
}
Based on your Database type change the connection details
Follow this Link for creating JDBC Connection and Inserting data
If you did the above steps please ignore this..
Related
I'm working in one quiz game. There is question maker window. Which works good for saving question. But when want update one of text Field and press save, than error is happening. something is wrong with syntax?!
void insertCell(String tableNamer, String column, String value, int id) throws ClassNotFoundException, SQLException{
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:file:C:/Users/Juris Puneiko/IdeaProjects/for_my_testings/src/sample/DB/Questions/For_Private/Easy", "Juris", "1");
PreparedStatement ps = conn.prepareStatement("UPDATE ? SET ? = ? where ID = ?");
ps.setString(1, tableNamer);
ps.setString(2, column);
ps.setString(3, value);
ps.setInt(4, id);
ps.executeUpdate();
ps.close();
conn.close();
}
org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "UPDATE ?[*] SET ? = ? WHERE ID = ? "; expected "identifier"; SQL statement:
UPDATE ? SET ? = ? where ID = ? [42001-196]
What is this >>> [*]?
What does it mean?
String sql = "UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, value);
ps.setInt(2, id);
ps.executeUpdate();
ps.close();
conn.close();
The placeholders can only be used for values in most SQL databases, not for identifiers like table or column names:
"UPDATE myTable SET myCol = ? where ID = ?" -- OK
"UPDATE ? SET ? = ? where ID = ?" -- not OK
The reason is that those parameters are also used for prepared statements, where you send the query to the database once, the database "prepares" the statement, and then you can use this prepared statement many times with different value parameters. this can improve DB performance because DB can compile and optimize the query and then use this processed form repeatedly - but to be able to do this, it needs to know names of the tables and columns involved.
To fix this, you only leave the ?s in for the values, and you concatenate the tableNamer and column manually:
"UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?"
Keep in mind though that by doing this, tableNamer and column are now potentially vulnerable to SQL injection. Make sure that you don't allow user to provide or affect them, or else sanitize the user input.
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!
com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'IDPaciente'
I am getting this exception. This is my code:
String query = "INSERT INTO Paciente('IDPaciente', 'NomePaciente', 'IdadePaciente', 'LocalidadePaciente') VALUES('"+IDTextField.getText()+"', '"+NomeTextField.getText()+"', '"+IdadeTextField.getText()+"', '"+LocalidadeTextField.getText()+"')";
try
{
st = con.DatabaseConnection().createStatement();
rs = st.executeQuery(query);
}
I suspect the problem might be in the query itself.
I have searched a lot and couldn't find the solution to my problem. I have tried refreshing the cache, changing permissions within the schema, restarting sql server (I am using sql server management studio 2012), I am correctly connected to my database, and nothing seems to work.
What could I be doing wrong?
Thank you!
Remove quotes , try :
String query = "INSERT INTO Paciente(IDPaciente, NomePaciente, IdadePaciente, LocalidadePaciente) VALUES('"+IDTextField.getText()+"', '"+NomeTextField.getText()+"', '"+IdadeTextField.getText()+"', '"+LocalidadeTextField.getText()+"')";
try
{
st = con.DatabaseConnection().createStatement();
rs = st.executeQuery(query);
}
Remove also quotes for INT values.
Your code is not secure, you can easily get Syntax error or SQL Injection I suggest to use PreparedStatement instead.
You have a problem in your Query, the columns should not be between '' so you can use this instead :
String query = "INSERT INTO Paciente(IDPaciente, NomePaciente, IdadePaciente, "
+ "LocalidadePaciente) VALUES(?, ?, ?, ?)";
try (PreparedStatement insert = con.prepareStatement(query)) {
insert.setString(1, IDTextField.getText());
insert.setString(2, NomeTextField.getText());
insert.setString(3, IdadeTextField.getText());
insert.setString(4, LocalidadeTextField.getText());
insert.executeUpdate();
}
If one of your column is an int you have to use setInt, if date setDate, and so on.
You have four problems, though only the first is giving you the current error:
Single-quotes (') are for quoting text literals, not column names. In MS SQL Server, you can quote column names using double-quotes (") or square brackets ([]), but you don't need to quote them at all.
To prevent SQL Injection attacks, where hackers will steal your data and delete your tables, and to prevent potential syntax errors, never build a SQL statement with user-entered strings, using string concatenation. Always use a PreparedStatement.
Always clean up your resources, preferably using try-with-resources.
Don't use executeQuery() for an INSERT statement. Use executeUpdate(). As the javadoc says:
Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.
So, your code should be:
String query = "INSERT INTO Paciente" +
" (IDPaciente, NomePaciente, IdadePaciente, LocalidadePaciente)" +
" VALUES (?, ?, ?, ?)";
try (PreparedStatement st = con.DatabaseConnection().prepareStatement(query)) {
st.setString(1, IDTextField.getText());
st.setString(2, NomeTextField.getText());
st.setString(3, IdadeTextField.getText());
st.setString(4, LocalidadeTextField.getText());
st.executeUpdate();
}
Remove the quotes from your column names.
"INSERT INTO Paciente(IDPaciente, NomePaciente, IdadePaciente, LocalidadePaciente) VALUES('"+IDTextField.getText()+"', '"+NomeTextField.getText()+"', '"+IdadeTextField.getText()+"', '"+LocalidadeTextField.getText()+"')"
The Column names are does not typed within quotes, Remove them and try again.
Demo:-
Create table MyTable (id int , name varchar (50))
go
insert into MyTable (id,name) values (1 , 'ahmed')
Result:-
(1 row(s) affected)
Try insert them again with quotes.
insert into MyTable ('id','name') values (1 , 'ahmed')
Result:-
Msg 207, Level 16, State 1, Line 3
Invalid column name 'id'.
Msg 207, Level 16, State 1, Line 3
Invalid column name 'name'.
Just looking for a little help,
Created an application in JAVA and using a jTable to gather data from myphp database, I am using Insert, update and delete SQL commands so the user is able to manipulate data in the table.
Delete works perfectly, however I am having some trouble with my update and insert commands, just wondering if anyone can see if im using the ("'+) incorrectly, im not as eagle eyed as someone more experienced so just seeing if anyone can shed some light :)
Thanks!
INSERT CODE :
String query = "INSERT INTO `supplier`(`Company Name`, `Contact`, `Address`, `Postcode`, `Phone`) VALUES ('"+jTextField_SupplierCompany.getText()+"','"+jTextField_SupplierContact.getText()+"',"+jTextField_SupplierAddress.getText()+"','"+jTextField_SupplierPostcode.getText()+"',"+jTextField_SupplierPhone.getText()+")";
UPDATE CODE:
String query = "UPDATE `supplier` SET `Company Name`='"+jTextField_SupplierCompany.getText() + "',`Contact`='"+jTextField_SupplierContact.getText() + "',`Address`="+jTextField_SupplierAddress.getText() + "',`Postcode`="+jTextField_SupplierPostcode.getText() + "',`Phone`="+jTextField_SupplierPhone.getText() + " WHERE `ID` = "+jTextField_SupplierID.getText();
ERROR:
The error is throwing is the misuse of the WHERE clause in the "UPDATE" statement... May be obvious to some however cant get my head around it.
To avoid these type of syntax errors, or any SQL Injection, you can use PreparedStatement instead, it is so simple and so helful :
String query = "INSERT INTO `supplier`(`Company Name`, `Contact`, `Address`, `Postcode`, `Phone`) "
+ "VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstm = conn.prepareStatement(query)) {
pstm.setString(1, jTextField_SupplierCompany.getText());
pstm.setString(2, jTextField_SupplierContact.getText());
pstm.setString(3, jTextField_SupplierAddress.getText());
pstm.setString(4, jTextField_SupplierPostcode.getText());
pstm.setString(5, jTextField_SupplierPhone.getText());
pstm.executeUpdate();
}
Your error happen because you forgot to close your String with '' check your query and you will see :
+"', " + jTextField_SupplierAddress.getText() + "'
//--^--------------------------------------------^
You Missed the Single quote in query
use this for insert
String query = "INSERT INTO supplier(Company Name, Contact, Address, Postcode, Phone) VALUES ('"+jTextField_SupplierCompany.getText()+"','"+jTextField_SupplierContact.getText()+"','"+jTextField_SupplierAddress.getText()+"','"+jTextField_SupplierPostcode.getText()+"','"+jTextField_SupplierPhone.getText()+"')";
Use this for update
String query = "UPDATE 'supplier' SET 'Company Name='"+jTextField_SupplierCompany.getText() + "',Contact='"+jTextField_SupplierContact.getText() + "',Address='"+jTextField_SupplierAddress.getText() + "',Postcode='"+jTextField_SupplierPostcode.getText() + "',Phone='"+jTextField_SupplierPhone.getText() + "' WHEREID` = '"+jTextField_SupplierID.getText()+"'";
I am trying to insert some values into Oracle DB from Java using the following JDBC statement:
String SQL_PREP_INSERT = "INSERT INTO ABC.TEST (LOG_ID, SESSION_ID,USER_ID) VALUES"
+ " (ABC.logid_seq.nextval, ?, ?)";
stmt = con.prepareStatement(SQL_PREP_INSERT);
stmt.setString(1, sessionId);
stmt.setString(2, userid);
stmt.execute();
stmt.close();
The sequence is created as follows:
create sequence ABC.logid_seq
minvalue 1 maxvalue 9999999999999999999999
increment by 10 start with 10 cache 20 noorder nocycle ;
I am getting the following error,
java.sql.SQLException: ORA-00942: table or view does not exist
But when I try to insert into the table manually, it's successful.
insert into ABC.test(LOG_ID,SESSION_ID,USER_ID) values
(VZPPTL.logid_seq.nextval,'test_session', '001');
What's the problem?
Possibly looking at the wrong table or database. Are you sure your looking at the right database from the code?
In prepare statement no need to give schema name(In this case ABC).
Try this, it might work.
String SQL_PREP_INSERT = "INSERT INTO TEST (LOG_ID, SESSION_ID,USER_ID) VALUES"
+ " (logid_seq.nextval, ?, ?)";