I'm looking for help to insert json data into postgres table using java program. I have tried with following code but cannot find any data is inserted in to the table. I have very little experience in programming. Can some one help me to modify my program to make it work?
here is my code.
enter code here stmt = c.createStatement();
String sql = "CREATE TABLE jason " +
"(ID INT NOT NULL," +
" NAME json NOT NULL)";
stmt.executeUpdate(sql); //updates the table
//json data----------------
String[] MESSAGE = {"{\"customer_name\": \"John\", \"items\": { \"description\": \"milk\", \"quantity\": 4 } }"};
sql = "INSERT INTO jason (ID,NAME) "
+ "VALUES (1,::MESSAGE );";
stmt.executeUpdate(sql);
You have problem with syntax here, please read this instruction: https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html
It's should be:
PreparedStatement pstmt = con.prepareStatement("INSERT INTO jason (ID,NAME) VALUES (1, ?1);");
pstmt.setString(1, yourJsonString)
To use parameters in a statement, you need to use a prepared statement:
java.sql.PreparedStatement stmt = conn.prepareStatement("INSERT INTO jason (ID,NAME) VALUES (1,?)" );
stmt.setString(1, "{\"customer_name\": \"John\", \"items\": { \"description\": \"milk\", \"quantity\": 4 } }");
stmt.executeUpdate();
Related
statement.executeUpdate("INSERT INTO LOGIN VALUES(" + jTextField1.getText() + ",'" + jTextField2.getText() + "'," + jTextField3.getText() + ")");
I have this line and I am trying to do this line prepared statement but I am not able to do it.
What I did is this :
PreparedStatement pstmt = con.prepareStatement("UPDATE Login
SET login_id = ? WHERE username = ?");
the sql table is this
CREATE TABLE login(
login_id INTEGER PRIMARY KEY,
username varchar(150) NOT NULL,
password varchar(150) NOT NULL
);
This folwoing code should be encapsuled in a ty catch statment
Also i hope you add a password hashing function to your code, every thing else is very insecure.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO LOGIN VALUES (?,?,?)");
pstmt.setInt (1, Integer.parseInt(jTextField1.getText()));
pstmt.setString (2, jTextField2.getText());
pstmt.setString (3, jTextField2.getText()));
// execute the preparedstatement
pstmt.execute();
observed parameterized object to avoid SQL Injections. just a bunch of security. although that one, you have provided is Okay for learning purposes.
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!
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'm having trouble inserting data inside my database..this is my codes looks like..
rs = stat.executeQuery("Select * from students;");
while (rs.next()) {
idNum = rs.getString("idNum");
stat.executeUpdate(
"INSERT INTO record VALUES (null,'" + idNum + "','" + descript +
"'," + value + ",'" + user.getText() + "','" + timeStamp + "')"
);
}//while
As you can see I want to insert a data for every student rs = stat.executeQuery("Select * from students;"); and get all their student number idNum = rs.getString("idNum"); this is what inside the students table:
idNum..............Name
11000001.........Leonardo
11000002.........David
11000003.........Robert
11000004.........Anna
11000005.........May
now when I get all their idNum I want them to be inserted inside the table record that will looks like this:
idNum.........descript.........amount........blablablabla
11000001.......Fee...............30
11000002.......Fee...............30
11000003.......Fee...............30
11000004.......Fee...............30
11000005.......Fee...............30
the problem is only the first idNum is being inserted inside the table record like this:
idNum.........descript.........amount........blablablabla
11000001.......Fee...............30
You shoulkd not use the same statement object stat twice: once you are reusing is to perform the update (in your case the insert) it closes the resultset you are looping over.
You can use a single statement to copy the data.
(Using parameters avoids formatting problems with strings containing special characters.)
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO record SELECT NULL, idNum, ?, ?, ?, ? FROM students");
ps.setString(1, descript);
ps.setInt (2, value);
ps.setString(3, user.getText());
ps.setString(4, timeStamp);
ps.execute();
Use an ArrayList to store all idNum from students table. Then loop through the list to insert into record table.
I need to use an INSERT statement, and 2 of the records in this statement are fields which are calculated in the program, and need to be added to the database.
System.out.println("Executing....");
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01', PKmod, PKexpo)";
stmt.executeUpdate(sql);
'PKmod' and 'PKexpo' are BigInteger fields whose value is calculated in the java program, how can I add these values to the database?
Thanks for any help! :)
Please do not insert sqls this way. Use prepared statement. Change your sql to use "?" markers instead of concatenating values.
It depends on the DBMS. For mysql perhaps BIGINT should suffice?
http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html
You need to concatenate the string!!!!
So do as follows:
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01',"+ PKmod+", "+PKexpo+")";
System.out.println("Executing....");
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01', "
+ PKmod
+ ", "
+ PKexpo
+ ")";
stmt.executeUpdate(sql);
// First Check That PKmod & PKexpo values are not Zero Or Null.
System.out.println("Executing....");
String sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01'," + PKmod + "," + PKexpo +")";
PreparedStatement pStmt = null;
pStmt = con.prepareStatement(sql);
pStmt.executeUpdate();
closePreparedStatement(pStmt);