I have a Collection and I want to write Nodes' values into a mysql table. Right now I connect to the database, create a statement and then for each Node in the collection I run
// open the connection then
Statement statement = connect.createStatement();
for (Node n : vertices) {
statement.execute("INSERT INTO " + table + " (name, department) values ('" + n.getName() + "', '" + n.getOrgId() + "')");
}
// then I close the connection
I am wondering if is there a more efficient method to deal with such a task.
Use prepared statements:
String query = "insert into " + table + " (name, department) values (?,?)";
try(PreparedStatement ps = connection.prepareStatement(query)) {
for(Node n : vertices) {
ps.setString(1, n.getName());
ps.setInt(2, n.getOrgId());
ps.addBatch();
}
ps.executeBatch();
} catch(SQLException e) {
// Exception handling
}
Notice that because of the way your query is built it is still vulnerable to SQL injection attacs (because you are building the string with a variable table). I recommend you either remove the table variable or take measures to ensure that that variable is never visible by any user of your program.
Try to prepare the query for a multiple insert, then execute it at once:
String query = "INSERT INTO " + table + " (name, department) values";
for (Node n : vertices) {
query += " ('" + n.getName() + "', '" + n.getOrgId() + "')");
}
statement.execute(query);
You can insert multiple rows at the same time.
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
Check this Link
Related
I am trying to compare the screen values input against the value stored in DB. Currently i am trying this code:
cell = sheet.getRow(i).getCell(2);
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection ("jdbc:mysql://madison-dev.czr6vej2htnn.us-east-1.rds.amazonaws.com:3306/madisondb","madisonadmin","t4xuw94$");// + "databasename=madison-dev.czr6vej2htnn.us-east-1.rds.amazonaws.com";
Statement st = con.createStatement();
ResultSet Rs = st.executeQuery("select name, zipcode, state, city, street from business_master where user_id =(\r\n" +
"select id\r\n" +
"from user_master\r\n" +
"where email = 'cell.getStringCellValue()') \r\n");
while (Rs.next()) {
// System.out.println(Rs.getString(1) + " " + Rs.getString(2) + " " + Rs.getString(3) + " "
// + Rs.getString(4) + " " + Rs.getString(5));
System.out.println(Rs.getString(0));
}
The screen is not showing any values.. and when i am trying to print System.out.println(Rs.getString(3)) outside of the loop it gives me an error
java.sql.SQLException: Illegal operation on empty result set.
You are trying to find all the rows where the email address is literally the text 'cell.getStringCellValue()' rather than the value returned by that method.
Whilst you code assemble your query string, that lays you open to SQL injection attacks. Use a prepared statement instead
PreparedStatement st = con.prepareStatement(
"select name, zipcode, state, city, street from business_master where user_id =(" +
"select id " +
"from user_master " +
"where email = ?)");
st.setString(1, cell.getStringCellValue());
ResultSet Rs = st.executeQuery();
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'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
I am doing java project in NetBeans 8 using databases and GUI.The problem is appearing when I search through the database and add the found values to JTable: all values are being added only to first column of JTable while I need them added separately to corresponding columns. I tried getColumnCount() and it also gave me 1 meaning that I have only one column. How to add database values to JTable's corresponding columns?
I've tried all the populating functions adviced here
My code:
jTable1 = new javax.swing.JTable();
String sql = "SELECT (flight_id, plane_name, dep_city, arival_city, date_month, date_day, eclassnumberofseats, bclassnumberofseats, fclassnumberofseats) FROM flight "
+ "WHERE (dep_city = '" + SearchFlight.getFromCity() + "' AND "
+ "arival_city = '" + SearchFlight.getToCity() + "' AND "
+ "date_month = '" + SearchFlight.getMonth() + "');";
PreparedStatement stat = conn.prepareStatement(sql);
ResultSet rs = stat.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs)
);
jScrollPane1.setViewportView(jTable1);
SearchFlight is a GUI class, and its methods return strings obtained in GUI.
DbUtils.resultSetToTableModel(rs)is a method in net.proteanit.sql.DbUtils;
So, it is expected that the data will be filled into 9 columns, hoewever it fills all the data into one column.
SELECT ( ... )
must be
SELECT ....
And better use the PreparedStatement as intended. Otherwise SQL injection still is possible. And try-with-resources closes the things under all circumstances.
String sql = "SELECT flight_id, plane_name, dep_city, arival_city, date_month, "
+ "date_day, eclassnumberofseats, bclassnumberofseats, fclassnumberofseats "
+ "FROM flight "
+ "WHERE dep_city = ? AND "
+ "arival_city = ? AND "
+ "date_month = ?";
try (PreparedStatement stat = conn.prepareStatement(sql)) {
stat.setString(1, SearchFlight.getFromCity());
stat.setString(2, SearchFlight.getToCity());
stat.setString(3, SearchFlight.getMonth());
try (ResultSet rs = stat.executeQuery()) {
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
}
I am connecting to a SQLite database through java using JDBC.
Schema:
WorkInfo(id, job, salary)
Person(id, name)
This query below runs fine in my database, but when I try it with JDBC:
ResultSet rs = statement.executeQuery("select * from Person join workInfo on (Person.id=WorkInfo.id)");
while(rs.next()){
System.out.println("id: " + rs.getInt("Person.id")); //column does not exist
System.out.println("name: " + rs.getString("name")); //works fine
Output:
If using person.id: no such column: 'person.id'
Without specifying: ambiguous column name 'id'
I've tried using both WorkInfo and Person and using aliases but it keeps throwing the same ambigious column name (if left as id) or column does not exist.
It's always a good practice to explicitly retrieve the columns you want. I would change the query to be:
ResultSet rs = statement.executeQuery("select info.id, info.job, info.salary, "
+ "person.id, person.name from Person person join workInfo info "
+ "on person.id=info.id");
while(rs.next()){
System.out.println("id: " + rs.getInt(4));
System.out.println("name: " + rs.getString(5));
In this case, you can use the column index instead of the label.
Or using the AS clause:
ResultSet rs = statement.executeQuery("select info.id, info.job, info.salary, "
+ "person.id as personId, person.name as personName "
+ "from Person person join workInfo info "
+ "on person.id=info.id");
while(rs.next()){
System.out.println("id: " + rs.getInt("personId"));
System.out.println("name: " + rs.getString("personName"));
After a day of working on this, I achieved it by using resultSet.getMetaData().
private int getIndexFromMeta(String column) {
try {
ResultSetMetaData meta = resultSet.getMetaData();
String[] subs = column.split("\\.", -1);
String tableName = subs[0];
String columnName = subs[1];
for (int i = 1; i <= meta.getColumnCount(); i++) {
if (meta.getTableName(i).equals(tableName) && meta.getColumnName(i).equals(columnName)) {
return i;
}
}
} catch (SQLException e) {
Log.trace(e);
}
return 0;
}
It seems like the ResultSet you're getting back holds the following columns:
id
name
id
job
salary
You have two columns named "id" (none named "Person.id"), so when you try to get its' value you either
Ask for "id" which is ambiguous (which id?)
Ask for "Person.id" which does not exist
Simply try specifying in your query the columns you want and giving them unique aliases. For example:
ResultSet rs = statement.executeQuery("select Person.id AS 'personid', name from Person join workInfo on (Person.id=WorkInfo.id)");
while(rs.next()){
System.out.println("id: " + rs.getInt("personid"));
System.out.println("name: " + rs.getString("name"));