How to insert Java ArrayList into a MySQL table? - java

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();
}

Related

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);
...

Java: error inserting data into MySQL

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();

Is it possible to insert records to MySQL with different parameter (keys & values) each time using the same insert function in Java?

I am trying to find out if it is possible to use the same insert function each time with new different parameters in java 8 & MySQL. I know it is possible in PHP as I have the PHP code below :
this is the array records:
$Customer_details=[
'firstname' => $Firstname,
'lastname'=> $lastname,
'phone' => $phone,
'email' => $email,
'password'=> $hash
];
After created the class object which is $object2 this is the records:
$object2->insert($pdo,'customer',$Customer_details);
The following code is the PHP insert function code:
function insert( $pdo, $table, $record) {
$keys = array_keys( $record);
$values = implode( ', ' , $keys);
$valuesWithColon = implode( ', :' , $keys);
$query = 'INSERT INTO ' . $table . ' (' . $values . ') VALUES (:' .
$valuesWithColon . ')' ;
$stmt = $pdo->prepare( $query);
$stmt->execute( $record);
return $stmt;
}
Can anybody just show me an example of the same thing in java, Please?
Yes, you can do that in much the same way you would achieve it with php, as #lexicore commented, a common pattern for parameterised sql queries in Java is to use PreparedStatements
Here is an example.. you would just need to wrap the code in that example in a function to make it reusable like your php example..
https://alvinalexander.com/java/java-mysql-insert-example-preparedstatement
public void insert(String fname, String lname, Date created, boolean isAdmin, int points) {
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
// create a sql date object so we can use it in our INSERT statement
Calendar calendar = Calendar.getInstance();
java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());
// the mysql insert statement
String query = " insert into users (first_name, last_name, date_created, is_admin, num_points)"
+ " values (?, ?, ?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, fname);
preparedStmt.setString (2, lname);
preparedStmt.setDate (3, created);
preparedStmt.setBoolean(4, isAdmin);
preparedStmt.setInt (5, points);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
}
I wrote this about a year ago, but I think this is what your looking for.
Ibelieve youwant to changeValuesto List<Object and use a switch statement with instanceOfto parse through that.
private String insert(String tableName, List<String> columns, List<String> values){
StringBuilder stringBuilder = new StringBuilder("INSERT INTO " + tableName + " (");
for(String column :columns){
stringBuilder.append(column + ",");
}
stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(","));
stringBuilder.append(") VALUES (");
for(String value : values){
stringBuilder.append(value + ",");
}
stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(","));
stringBuilder.append(")");
return stringBuilder.toString();
}
Of as previously mention use this and make the second loop:
for(int z =0; z < columns.size(); z++){
stringBuilder.append("?,");
}
To use with PreparedStatements knowing what I know now, I would choose the latter.

How to insert data into specific fields of mysql table from the first row in Java

I have a table called Cast with these fields : Id, CastName, CastImdbId. This table already has many records. Now, I would like to add 3 new fields to this table which are (gender, castBirthDate, castBirthPlace). The problem is that "insert into" add new data to the end of table (after the last record), but I need to add these data starting from the first record. Could someone please let me know if it is possible and how?
This is part of my code which has the problem:
try{
String query = "INSERT into Cast (gender, castBirthDate, castBirthPlace)" + "VALUES (?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, gender);
preparedStmt.setString (2, dateOfBirth);
preparedStmt.setString (3, placeOfBirth);
preparedStmt.executeUpdate();
}catch (Exception e){
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
Use an ALTER statement on the table.
Example
ALTER TABLE Cast
ADD (gender varchar2(1), //Depending on "F" or "Female"
castBirthDate Date,
castBirthPlace varchar2(50));
Then UPDATE the new fields. Which can be done in many ways. Avoid the INSERT.
UPDATE in jdbc is like this:
StringBuilder sql = new StringBuilder("");
sql.append("UPDATE Cast ");
sql.append("SET gender = ?, ");
sql.append("castBirthDate = ?, ");
sql.append("castBirthPlace = ? ");
sql.append("WHERE actor_id = ?"); //Assuming...
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, gender);
preparedStmt.setString (2, dateOfBirth);
preparedStmt.setString (3, placeOfBirth);
preparedStmt.executeUpdate();
Do you want to set those fields values to the existing records? Then you might want to UPDATE them.
As the name implies, an INSERT statement will add new rows at the end of the table.
UPDATE will modify the row or rows you specify, changing the values on the fields you specify.
UPDATE table SET column1='value1', column4='value2' WHERE column2='thisValue'
In your case, let's say you want to set 'Female' to "Halle Berry"
UPDATE Cast SET gender='Female' WHERE CastName='Halle Berry'
You should of course use IDs and references like F for 'female' and not the whole word.

How to insert in database sqlite3

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.

Categories

Resources