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'.
Related
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..
I am working with a postgres database and I'm using JDBC. Most things are working fine, but I'm getting the following error with this piece of code and it seems to be that I'm not properly using setString/setDate with a $ style parameterized query. Without further ado, here is the code
(The variables not initialized here were initialized correctly ahead of this method call).
String query = "INSERT INTO \"tracks\" (\"artist\", \"album\", \"name\", \"listened_at\", \"created_at\", \"updated_at\", \"url\", \"image_url\") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING \"id\"";
PreparedStatement statement = connection.prepareStatement(query);
java.sql.Date current = new java.sql.Date((new Date()).getTime());
java.sql.Date sqlListenedAt = new java.sql.Date(listenedAt.getTime());
statement.setString(1, artist);
statement.setString(2, album);
statement.setString(3, name);
statement.setDate(4, sqlListenedAt);
statement.setDate(5, current);
statement.setDate(6, current);
statement.setString(7, url);
statement.setString(8, imageUrl);
and the error that I'm getting is as follows
org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
Is there a way to properly use a INSERT INTO "table" ("column_a", "column_b") VALUES ($1, $2) style statement with JDBC?
String query = "INSERT INTO tracks (artist, album, name, listened_at, created_at, updated_at, url, image_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id";
I think the rest of your code is probably okay. Two basic comments:
-You only need to quote your table / column names when they are otherwise reserved words in SQL. The way you wrote it is really hard to read.
-JDBC uses ? for placeholders. I've never seen $1 etc. Maybe that works, but I don't think so.
I have created such statement:
String query = "INSERT INTO ZMONES (ID, PAVADINIMAS, SLAPTAZODIS) VALUES("
+sum+" ,"+a+", "+b+")";
where variable sum is an integer ID in the database's table and a and b are two string values that are to be added. I am executing this statement as such: stmt.executeUpdate(query);
However this error pops out:
Column 'PERSON' is either not in any table in the FROM list or appers
within a join specification and is outside the scope of the join
specification or appears in a having clause and is not in the GROUP BY
list. If this is a CREATE or ALTER TABLE statement then 'PERSON' is
not a column in the target table.
I do understand that Java interprets it as a column's name, I do not however, understand why this happens? I have searched for in this in stackoverflow and most questions deal with text and not string variables.
The error that you ran into can be corrected easily as follows (assuming sum is a number):
String query = "INSERT INTO ZMONES (ID, PAVADINIMAS, SLAPTAZODIS) VALUES("
+sum+" ,'"+escape(a)+"', '"+escape(b)+"')";
Where escape(String) is the following method:
public String escape(String string) {
// This works in most databases, although some require you to escape apostrophes via \'
return string == null ? null : string.replace("'", "''");
}
A note on SQL injection
But please! Don't do that. Use a PreparedStatement and proper bind variables instead of concatenating your input into your SQL statements. Why?
Because of SQL injection
Because of performance considerations
Here's how:
try (PreparedStatement s = connection.prepareStatement(
"INSERT INTO ZMONES (ID, PAVADINIMAS, SLAPTAZODIS) VALUES (?, ?, ?)")) {
s.setInt(1, sum);
s.setString(2, a);
s.setString(3, b);
s.executeQuery();
}
You need to surround strings with quotation marks:
String query = "INSERT INTO ZMONES (ID, PAVADINIMAS, SLAPTAZODIS) VALUES("+sum+", '"+a+"', '"+b+"')";
I've connected a java project (using netbeans) to a MySQL database, but I'm having trouble inserting data.
If i use this code it inserts just fine:
String update = "insert into expenses(Expense,Cost,Purchase_Date,Description)\n" +
"values('milk', 3.18, '2015-01-23','Grocery');";
but when i try and replace the insert values with these predefined values:
String ExpenseName;
Double ExpenseCost;
String ExpenseDate;
String ExpenseType;
and then use this code to insert the values:
String update = "insert into expenses(Expense,Cost,Purchase_Date,Description)\n" +
"values('"+ExpenseName+"',"+ExpenseCost+",'"+ExpenseDate+"','"+ExpenseType+"');";
I get the error: SQLException: Column 'Cost' cannot be null
my cost field in my database is defined as decimal(15,2)
Even more annoyingly, when i try and use this code to update as a test:
String update = "insert into expenses(Expense,Cost,Purchase_Date,Description)\n" +
"values('"+ExpenseName+"',3.18,'"+ExpenseDate+"','"+ExpenseType+"');";
i get another error saying:
SQLException: Data truncation: Incorrect date value: 'null' for column 'Purchase_Date' at row 1
this is confuses me a lot because through the database i have no issues with updating the Purchase_Date field in the expenses table with a '2015-01-23'. if its of any use that field is of type date. perhaps it's because the date object in my java is string?
You really should use a PreparedStatement
PreparedStatement pst= con.prepareStatement(
"insert into expenses(Expense,Cost,Purchase_Date,Description)" +
" values(?, ?, ?,?)");
pst.setString(1, ExpenseName);
pst.setDouble(2, ExpenseCost);
pst.setDate(3, new java.sql.Date(ExpenseDate.getTime()));
pst.setString(4, ExpenseType);
pst.executeUpdate();
Also, you should inititalize your variables properly.
Assuming that they are declared as fields, you should initialize them as :
String ExpenseName="SomeName";
Double ExpenseCost=1.8;
Date ExpenseDate=new Date();
String ExpenseType="Some Type";
Uninitialized variables could be the source of the SQLException, because ExpenseName and ExpenseDate would be concatenated as "null" in your SQL string.
You should always use a PreparedStatement to insert/ update data and not use String concatenation. This will not only help you with formatting the data correctly but also protect you against SQL injection attacks.
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, ?, ?)";