Proper way to add data to a table in postgreSQL using JDBC? - java

This is my first post here, if my formatting is not correct/ hard to read, I will change it. Please let me know.
I have been playing with JDBC trying to add basic data to a database, using user input data. The user provides first and last name, email, and a user id is generated using the random function.
The database was created using postgreSQL. I'm trying to add to a table called accounts, which contains the following columns - user_id (integer), first_name (varchar(100)), last_name (varchar(100)), email (varchar(500)).
My program is able to connect to the database successfully, but it's not able to add data to the table.
in the following code, firstName, lastName, and eMail are all strings, while sID is an int.
state = conx.prepareStatement("INSERT INTO accounts VALUES ("+ sID +","+ firstName + "," + lastName + "," + eMail) + ")");
s.executeUpdate();
Normally, I'd hope the data would be added to the table so we can call it a day, but I'm getting an error.
org.postgresql.util.PSQLException: ERROR: column "v" does not exist
Position: 36
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:120)
at Main.main(Main.java:49)
org.postgresql.util.PSQLException: ERROR: column "v" does not exist
Position: 36

Use ? for parameters instead of concatenating their values. Also, you should name the columns in the INSERT statement. For example:
s = conx.prepareStatement(
"INSERT INTO accounts (id, first_name, last_name, email) " +
"VALUES (?, ?, ?, ?)"
);
s.setInt(1, sID);
s.setString(2, firstName);
s.setString(3, lastName);
s.setString(4, email);
int affectedRows = s.executeUpdate();

Related

Problem with add data to mySql with String.format in Java

I have problem when i try to add data to mySql Table with String.format.
MySql table:
CREATE TABLE Product (
Product_id int AUTO_INCREMENT,
Name varchar(255),
Description varchar(255),
Price double(9,2),
Primary Key(Product_id)
);
Method, that adds a record to the table. Problem is with column price. In mysql i defined it: Double(9,2). When I add it like this, everything works fine.
public void insertProduct(Product product) {
this.databaseService.performDML(
String.format("INSERT INTO product (name,description,price) " +
"VALUES ('%s', '%s', '"+product.getPrice()+"')",
product.getName(),
product.getDescription())
);
}
but when adding looks like this, i have exception: "Data truncated for column 'Price' at row 1"
public void insertProduct(Product product) {
this.databaseService.performDML(
String.format("INSERT INTO product (name,description,price) " +
"VALUES ('%s', '%s', '%f')",
product.getName(),
product.getDescription(),
product.getPrice())
);
}
Can someone tell me the difference, and how i can add data properly with String.format?
Here's the conclusion, use prepared statements instead of building a string yourself for SQL statements.
But if you are really wondering about the difference between the two strings... the main difference is that the price gets padding zeros after the point for doubles if you use String.format() method.
You could simply print the two strings in console to see the difference.
For example, for the price is 12.345:
String.format("INSERT INTO product (name,description,price) " +
"VALUES ('%s', '%s', '"+product.getPrice()+"')",
product.getName(),
product.getDescription())
The first string gets "12.345".
String.format("INSERT INTO product (name,description,price) " +
"VALUES ('%s', '%s', '%f')",
product.getName(),
product.getDescription(),
product.getPrice())
The second string gets "12.345000".

How to add to INSERT INTO PRIMARY KEY AND FOREIGN KEY

So i have two tables: locations and employees i want locations_id to be the same in employees.locations_id, I am trying to make it all in one statement
the erros is this 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 'INSERT INTO employees(employees_id, locations_id) VALUES('e1598','')' at line 1
String sql = " INSERT INTO locations( locations_id , username, password, id, type_of_id, first_name, last_name, phone, email, date_of_birth, address, sex ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"
**Error here --->** + "INSERT INTO employees(employees_id,locations_id) VALUES (?,SELECT locations_id FROM locations INNER JOIN employees ON locations.locations_id =employees.locations_id)";
try {
MicroModelGUI micro = new MicroModelGUI();
PreparedStatement consulta = micro.connection.prepareStatement(sql);
consulta.setString(1, tflid.getText());
consulta.setString(2, tfuser.getText());
consulta.setString(3, tfpass.getText());
consulta.setString(4, tfid.getText());
consulta.setString(5, tftoid.getText());
consulta.setString(6, tffirst.getText());
consulta.setString(7,tflast.getText());
consulta.setString(8,tfphone.getText());
consulta.setString(9,tfemail.getText());
consulta.setString(10,tffdn.getText());
consulta.setString(11,tfaddress.getText());
consulta.setString(12,tfsex.getText());
consulta.setString(13,tfeid.getText());
int resultado = consulta.executeUpdate();
You should be using an INSERT INTO ... SELECT here:
INSERT INTO employees (employees_id, locations_id)
SELECT ?, l.locations_id
FROM locations l
INNER JOIN employees e ON l.locations_id = e.locations_id;
To the ? placeholder you would bind a value from your Java code. Note that while your version of SQL might support putting a scalar subquery into a VALUES clause, it is likely that your exact version would cause an error, as it would return more than one row.

SQL INSERT with loop with multiple rows

I'm trying to insert skeleton data into a database using jdbc.
So far my code is:
Statement st=con.createStatement();
String sql = "INSERT INTO student (studentid, titleid, forename, familyname, dateofbirth) "
+ "VALUES (1, 1, 'forename1', 'surname1', '1996-06-03');";
I need to create 100 entries for this and I'm not too sure how to go about doing it.
All I want is the student id, titleid, forename and familyname to increment by 1 until it reaches 100 entries with those rows filled in, date of birth doesn't need to be altered. I'm asking how to do a loop for this
General answer - You should use PrepareStatement instead of Statement and execute as batch.
Common way to insert multiple entry or execute
String sql = "INSERT INTO student (studentid, titleid, forename, familyname, dateofbirth) "
+ "VALUES (?, ?, ?, ?, ?);";
ps = connection.prepareStatement(SQL_INSERT);
for (int i = 0; i < entities.size(); i++) {
ps.setString(1, entity.get...());
...
ps.addBatch();
}
ps.executeBatch();
Important Note:
Why you should use PrepareStatement Over Statement
SQL Injection Example
There are two ways to do this. You can put your insert query inside a loop or you can put your loop inside an insert query. I have found that the better method depends on the database engine (but I've never used postresql) and the number of records you want to insert. You could bump up against the maximun query length or number of parameters or something.
The following code sample is ColdFusion, but it is intended to show the general idea of having a loop inside a query. You would have to write equivalent code in java.
<cfquery>
insert into yourtable
(field1
, field2
, etc)
select null
, null
, null
from SomeSmalllTable
where 1 = 2
<cfloop>
union
select <cfqueryparam value="#ValueForField1#">
, <cfqueryparam value="#ValueForField#">
, etc
</cfloop>
</cfquery>

Database value insertion Error

How can i manually insert values if not exist...i tried following code but it produce error.How can i insert values if not exist in the table
String sql1 = "CREATE TABLE IF NOT EXISTS admin " +
"(id INTEGER not NULL AUTO_INCREMENT, " +
" user_name VARCHAR(255), " +
" password VARCHAR(255), " +
" isAdmin BOOLEAN NOT NULL DEFAULT '0', " +
" memo VARCHAR(255), " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql1);
String insert="INSERT INTO admin IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
stmt.executeUpdate(insert);
it produce an error like
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 'IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'mem' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
String insert="INSERT INTO admin IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
should be
String insert="INSERT IGNORE INTO admin (id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
MySQL (and any other SQL implementation as well) doesn't support IF NOT EXISTS in INSERT queries.
your INSERT query must be
"INSERT IGNORE INTO admin (id,user_name,password,isAdmin,memo) VALUES (1,'admin','admin',1,'memo')"
What you want may be INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE....
The former will update an existing row if a duplicate insert is detected, while the latter will just throw away duplicate inserts.
In both cases, you'll have to create a UNIQUE constraint on the column you want to check for duplicates. If the UNIQUE is violated, the alternate function is invoked.

How to select a column in with a CLOB datatype

I have a table on my jsp page that will have a column populated by a database column with type CLOB. I am running into some trouble doing this, and have seen other questions asked about this, but the answers have not worked for me. Here is my statement where comments is a CLOB.
stmt = conn.prepareStatement("SELECT DISTINCT restriction, person, start_date, end_date, comments "
+ " FROM restrictions WHERE person = ? "
+ " AND (start_date BETWEEN TO_DATE (? , 'yyyy/mm/dd') AND TO_DATE (? , 'yyyy/mm/dd') "
+ " OR start_date < TO_DATE (? , 'yyyy/mm/dd') AND end_date IS NULL) " );
stmt.setString(1, Id);
stmt.setString(2, StartRest);
stmt.setString(3, EndRest);
stmt.setString(4, EndRest);
result = stmt.executeQuery();
And then I will have the columns in a while loop:
while (result.next()) {
restrictions = StringUtils.defaultString(result.getString("str_restriction"));
.......
// here is where I would get my Clob data from the query.
So, basically, I was wondering if there is a way to translate the CLOB in the query, or even in the java code, so it would be usable in my page.
The problem comes from the distint clause of the query, which can't be applied to a CLOB.
Check if the distinct keyword is really needed. Or maybe you could rewrite your query as
select restriction, person, start_date, end_date, comments from restrictions
where id in (select distinct id from restrictions where <original where clause>)
PS: next time, include the error message and your database in the question. I've been able to find the problem with a simple google search on "ora-00932 clob".

Categories

Resources