Java: error inserting data into MySQL - java

I am using eclipse to insert data into MySQL, and it is only inserting the last row of the data.
String countryCodeSql = "INSERT INTO session" + "(sessionTimestamp,countryCode,countryName,visitorID)" + "VALUES ('"+timeStamp+"','"+countryCode+"','" + countryName+"','" + visitorID+"')";
myStat.executeUpdate(countryCodeSql);
these are my lines of codes, but I think it should be working fine as the codes below worked and the data were inserted.
String timeStampSql = "INSERT INTO conversation" + "(timestamp)" + "VALUES ('" +timeStamp+"')";
myStat.executeUpdate(timeStampSql);

You can use the preparedStatement to insert data in the database when the data are dynamic. here is an example:
Connection connection = DriverManager.getConnection(DATABASE_URL,USERNAME,PASSWORD);
String query = "INSERT INTO session (sessionTimestamp,countryCode,countryName,visitorID) values(?,?,?,?)";
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setString (1, timeStamp);
preparedStmt.setString (2, countryCode);
preparedStmt.setString (3, countryName);
preparedStmt.setString (4, visitorID);
preparedStmt.execute();

Related

Get final query from executeBatch()

How to get the final batch SQL query from Spring boot SQL statement. I am connecting to PostgreSQL database with Java 8 and spring boot.
String sqlQuery = "insert into table1 (id, name) values (?, ?)";
PreparedStatement pstmt = connection.prepareStatement(sqlQuery);
pstmt.setInt(1, 1);
pstmt.setString(2, "name1");
pstmt.addBatch();
pstmt.setInt(1, 2);
pstmt.setString(2, "name2");
pstmt.addBatch();
pstmt.executeBatch();
System.out.println(pstmt);
Output:
insert into table1 (id, name) values (2, name2)
Expected Output:
insert into table1 (id, name) values (1, name1), (2, name2)
I am getting the last SQL query instead of the batch SQL query.

Change a line to prepared statement

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.

how to get the last insert id in java mysql

i am creating simple sales system. i have to get the last insert id but i couldn't get the id.when i tried the code i got the error of the console
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
i attached the code below what i tried so far
try{
int lastinsertid=0;
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con1=DriverManager.getConnection("jdbc:mysql://localhost/javasales","root","");
String query = " insert into sales_product (product, price)"
+ " values (?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = (PreparedStatement) con1.prepareStatement(query);
preparedStmt.setString (1, txtproduct.getText());
preparedStmt.setString (2, txtprice.getText());
preparedStmt.executeUpdate();
ResultSet rs = preparedStmt.executeQuery();
if (rs.next()) {
lastinsertid = (int) rs.getLong(1);
}
System.out.println("Inserted record's ID: " + lastinsertid);
}
catch(ClassNotFoundException coe)
{
System.out.println("odbc driver not found");
}
catch(SQLException sqe)
{
System.out.println(sqe);
}
You need to add Statement.RETURN_GENERATED_KEYS in con1.prepareStatement(query) that would result that you can get the generated key. You also should use only one of the following methods:
executeQuery
executeUpdate
Because there is no reason, to use booth methods.
After you done that you can get it like that:
...
PreparedStatement preparedStmt = con1.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
preparedStmt.setString (1, txtproduct.getText());
preparedStmt.setString (2, txtprice.getText());
preparedStmt.executeUpdate();
ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();
if (generatedKeyResult.next()) {
lastinsertid = generatedKeyResult.getInt(1);
}
System.out.println("Inserted record's ID: " + lastinsertid);
...

insert into database having large number of parameter

i have to insert data into database .Because sql statement VALUES(......) have 8 parameters . Is it proficient way to use insert statement ?
Class UserRegistration {
public void insertToDatabase(){
String sql=" INSERT INTO db1(......) Values(id,fname,lastname,username,password,usertype,email,contact,address )"
}
}
The correct way to do it in Java, assuming you're using JDBC, is to use a PreparedStatement.
String sql = "INSERT INTO db1" +
" (id,fname,lastname,username,password,usertype,email,contact,address)" +
" VALUES (?,?,?,?,?,?,?,?,?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt (1, id);
stmt.setString(2, fname);
stmt.setString(3, lastname);
stmt.setString(4, username);
stmt.setString(5, password);
stmt.setString(6, usertype);
stmt.setString(7, email);
stmt.setString(8, contact);
stmt.setString(9, address);
stmt.executeUpdate();
}

How to insert Java ArrayList into a MySQL table?

Could someone kindly tell me how can I insert the values of Arraylist into MySQL table as a single string?
E.g, insert "crime, drama, Action" into column "genres" of a table "featuredfilms_INFO".
This is a part of my code:
int i = 0;
List<String> genre = new ArrayList<String>();
.
.
.
Elements elms1 = doc.select("div.infobar");
Elements links1 = elms1.select("a[href]");
for (Element link1 : links1){
if (link1.attr("href").contains("/genre/")) {
genre.add(links1.get(i).text());
i++;
}
}
System.out.println("movie genres:" + genre);
.
.
try {
String query = "INSERT into featuredfilms_INFO (movieId, genres)" + "VALUES (?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, ID);
preparedStmt.setString (2, genre);
.
.
.
}
My problem is that I cannot use setString for genre since it is not of type string. I'm a bit confused since at the beginning I defined genre as string but after some search I found that in Java for dynamic arrays I have to use ArrayList.
Can someone explain me in detail what should I do and why?
Just join all the strings before inserting.
String comma="";
StringBuilder allGenres = new StringBuilder();
for (String g: genre) {
allGenres.append(comma);
allGenres.append(g);
comma = ", ";
}
String query = "INSERT into featuredfilms_INFO (movieId, genres)" + "VALUES (?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, ID);
preparedStmt.setString (2, allGenres.toString());
Maybe even
preparedStmt.setString (2, genre.toString());
would even be good enough, but the above solution gives you more freedom how to join the genres.
I guess you're confused because your List<String> is called genre and you try to insert it as is. This won't work. You need to insert every element from the List in your table.
Assuming you have declared and initialized ID variable and that List<String> genre is filled with the right values, then you should only traverse the list and insert every genre:
String query = "INSERT into featuredfilms_INFO (movieId, genres)" + "VALUES (?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, ID);
for (String realGenre : genre) {
preparedStmt.setString (2, realGenre);
preparedStmt.executeUpdate();
}

Categories

Resources