How to insert values from csv into database in java - java

I have tried the following code to split the csv values and now how do insert it in to DB? Do I have save the values in to separate variables to match column names? I am unable to figure out.
Note: I don't want to use any csv parser right now. I just want to do it manually
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
String name;
String email;
String phone;
String ID;
Connection con = OracleDBConnection.getConnection();
String query = "Insert into NEWSTUDENT values(?,?,?,?)";
PreparedStatement st = con.prepareStatement();
st.executeUpdate(query);
try {
BufferedReader bReader = new BufferedReader(new FileReader("1000rows.csv"));
while (bReader != null) {
String read;
try {
read = bReader.readLine();
if (read != null)
{
String[] array = read.split(",+");
for(String result:array)
{
System.out.println(result);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
finally
{
if (bReader == null)
{
bReader.close();
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
output:
1Kiriti
kiriti#gmail.com
880789939
Column names in Database:
Name Email Phone ID

Use Parepared statement and build a query in while Loop and execute it. For more on Prepared Statement please check Check this link
String sql = " INSERT INTO TABLE_(name,email,phone,id) VALUES(?,?,?,?) ";
try {
BufferedReader bReader = new BufferedReader(new FileReader("1000rows.csv"));
String line = "";
while ((line = bReader.readLine()) != null) {
try {
if (line != null)
{
String[] array = line.split(",+");
for(String result:array)
{
System.out.println(result);
//Create preparedStatement here and set them and excute them
PreparedStatement ps = yourConnecionObject.createPreparedStatement(sql);
ps.setString(1,str[0]);
ps.setString(2,str[1]);
ps.setString(3,str[2]);
ps.setString(4,strp[3])
ps.excuteUpdate();
ps. close()
//Assuming that your line from file after split will folllow that sequence
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
finally
{
if (bReader == null)
{
bReader.close();
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}

You can use Prepare Statement and set the value in parameter at each iteration:
Connection con = OracleDBConnection.getConnection();
String query = "Insert into NEWSTUDENT values(?,?,?,?)";
PreparedStatement ps=con.prepareStatement(query);
ps.setString(1,array[0]);
ps.setString(2,array[1]); // and so on
ps.executeUpdate();
If No of Rows are more you can also use Batch Processing :
String sql = "Insert into NEWSTUDENT values(?,?,?)";
PreparedStatement preparedStatement = null;
try{
preparedStatement =
connection.prepareStatement(sql);
preparedStatement.setString(1, "Gary");
preparedStatement.setString(2, "Larson");
preparedStatement.setString (3, "Test");
preparedStatement.addBatch();
preparedStatement.setString(1, "Stan");
preparedStatement.setString(2, "Lee");
preparedStatement.setString (3, 456);
preparedStatement.addBatch();
int[] affectedRecords = preparedStatement.executeBatch();
}finally {
if(preparedStatement != null) {
preparedStatement.close();
}
}

You can store your data in an array and bind them to your statement:
String query = "Insert into NEWSTUDENT values(?,?,?,?)";
PreparedStatement st = con.prepareStatement(query);
st.setString(1,array [0]);
st.setString(2,array[1]);
....
st.executeUpdate();
For more informations about prepared statements see the oracle documentation

Related

having trouble inserting values into table with syntax error

Everytime at around "composedLine = String.format("%s, %s, %s, %s, %s", composedLine,
values[0], values[1], values[2], values[3]);"
it produces "INSERT INTO airport VALUES (, ABR, Aberdeen Regional Airport, Aberdeen"
instead of "INSERT INTO airport VALUES (ABR, Aberdeen Regional Airport, Aberdeen"
which causes a syntax error when I use executeupdate due to the "," before the ABR.
import java.io.*;
import java.sql.*;
import java.util.*;
public class UsaDelayFlight {
public static Connection connectToDatabase(String user, String password, String database) {
System.out.println("------ Testing PostgreSQL JDBC Connection ------");
Connection connection = null;
try {
String protocol = "jdbc:postgresql://";
String dbName = "";
String fullURL = protocol + database + dbName + user;
connection = DriverManager.getConnection(fullURL, user, password);
} catch (SQLException e) {
String errorMsg = e.getMessage();
if (errorMsg.contains("authentication failed")) {
System.out.println("ERROR: \tDatabase password is incorrect. Have you changed the password string above?");
System.out.println("\n\tMake sure you are NOT using your university password.\n"
+ "\tYou need to use the password that was emailed to you!");
} else {
System.out.println("Connection failed! Check output console.");
e.printStackTrace();
}
}
return connection;
}
public static void dropTable(Connection connection, String table) throws SQLException {
Statement st = null;
try {
st = connection.createStatement();
boolean result = st.execute("DROP TABLE IF EXISTS " + table);
} catch (SQLException e) {
e.printStackTrace();
}
st.close();
}
public static void createTable(Connection connection, String tableDescription) throws SQLException {
Statement st = null;
try {
st = connection.createStatement();
boolean result = st.execute("CREATE TABLE IF NOT EXISTS " + tableDescription);
} catch (SQLException e) {
e.printStackTrace();
}
st.close();
}
public static ResultSet executeQuery(Connection connection, String query) {
System.out.println("DEBUG: Executing query...");
try {
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public static int insertIntoTableFromFile(Connection connection, String table,
String filename) {
int numRows = 0;
String currentLine = null;
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
Statement st = connection.createStatement();
// Read in each line of the file until we reach the end.
while ((currentLine = br.readLine()) != null) {
String[] values = currentLine.split(",");
System.out.println(Arrays.toString(values));
String composedLine = "INSERT INTO " + table + " VALUES (";
//String r = String.format("formatted values are %s", composedLine);
composedLine = String.format("%s, %s, %s, %s", composedLine,
values[0], values[1], values[2], values[3]);
System.out.println(composedLine);
//. . .
// Finally, execute the entire composed line.
numRows = st.executeUpdate(composedLine);
}
} catch (Exception e) {
e.printStackTrace();
}
return numRows;
}
// NOTE: You will need to change some variables from START to END.
public static void main(String[] argv) throws SQLException {
// START
// Enter your username.
String user = "";
// Enter your database password, NOT your university password.
String password = "";
/** IMPORTANT: If you are using NoMachine, you can leave this as it is.
*
* Otherwise, if you are using your OWN COMPUTER with TUNNELLING:
* 1) Delete the original database string and
* 2) Remove the '//' in front of the second database string.
*/
String database = "";
//String database = "";
// END
Connection connection = connectToDatabase(user, password, database);
if (connection != null) {
System.out.println("SUCCESS: You made it!"
+ "\n\t You can now take control of your database!\n");
} else {
System.out.println("ERROR: \tFailed to make connection!");
System.exit(1);
}
// Now we're ready to use the DB. You may add your code below this line.
createTable(connection, "delayedFlights (ID_of_Delayed_Flight varchar(15) not null, Month varchar(10), "
+ "DayofMonth int, DayofWeek int, DepTime timestamp, ScheduledDepTime timestamp, ArrTime int,"
+ "ScheduledArrTime timestamp, UniqueCarrier varchar(15) not null, FlightNum int, ActualFlightTime timestamp,"
+ "scheduledFlightTime timestamp, AirTime timestamp, ArrDelay timestamp, DepDelay timestamp, Orig varchar(15),"
+ "Dest varchar(15), Distance int, primary key (ID_of_Delayed_Flight), unique (UniqueCarrier));");
createTable(connection, "airport (airportCode varchar(15) not null, "
+ "airportName varchar(15), City varchar(15), State varchar(15), primary key (airportCode));");
insertIntoTableFromFile(connection, "airport", "airport");
String query = "SELECT * FROM delayedFlights;";
ResultSet rs = executeQuery(connection, query);
try {
while (rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
rs.close();
}
}
This code is a security vulnerability. Specifically, SQL injection. This is not how you do it.
The correct way also solves your problem in passing. Thus, solution: Do it the correct way, solves all your problems.
Correct way:
PreparedStatement ps = con.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?, ?)");
ps.setString(1, values[0]);
ps.setString(2, values[1]);
ps.setString(3, values[2]);
ps.setString(4, values[3]);
ps.executeUpdate();

Mysql database multiple successive requests fail

All of my database access methods have been working up until now. I have a string of n usernames separated by ";", and I want to make n separate select statements to check if the user is online or offline. However, when used, this method returns nothing (""). The database connection is working. Any solutions are welcome.
EDIT:
New method, still does not work:
public static String CheckOn(String users) {
String toreturn = "";
PreparedStatement stmt2 = null;
ResultSet rs2 = null;
try {
conn = Database.getDBConnection("test");
String sql = "SELECT name FROM sessions WHERE name=?";
stmt2 = conn.prepareStatement(sql);
String[] usarr = users.substring(1, users.length()).split(";");
for (int i = 0; i <usarr.length;i++){
if (usarr[i].equals("Empty")){
toreturn = toreturn + "-";
}
else{
stmt2.setString(1, usarr[i]);
rs2 = stmt2.executeQuery();
if (rs2.next()){
toreturn = toreturn + "y";
}
else{
toreturn = toreturn + "n";
}
rs2.close();
}
}
rs2.close();
stmt2.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} finally {
try {
if (stmt2 != null)
stmt2.close();
} catch (SQLException se2) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
return toreturn;
}

Inserting information from one mysql table to another

I am writing a program that will take in a student ID and verify if that ID exists in a mysql table. If it does exist, I would like to take the entire row that it exists in and copy that row to another table. Currently the program will just copy all rows in a table to the other. Any help appreciated. I have inserted a snippet of code below.
try {
String compareText = IDField.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
Statement stmt1 = conn.createStatement();
ResultSet rs1 = stmt1.executeQuery("select * from students where LUID='"+IDField.getText()+"' ");
boolean isPresent = rs1.next();
if (isPresent)
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
if (rows == 0)
{
System.out.println("Don't add any row!");
}
else
{
System.out.println(rows + " row(s)affected.");
conn.close();
}
//System.out.println("Already exists!!");
}
You could all do that in a single SQL statement:
INSERT INTO <Dest-Table>
(SELECT * FROM <Src-Table> WHERE ID=?);
It will only copy rows that exist.
I suspect it's due to this line:
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
As, if that line is parsed, the SELECT statement has no WHERE clause, and will therefore get every row, and therefore insert everything.
With Prepared statements
String sql = "INSERT INTO abc"
+ "(SELECT id1,id2 FROM pqr)";
ps1 = con.prepareStatement(sql);
int rs = ps1.executeUpdate();
if (rs > 0) {
update = true;
} else {
update = false;
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (ps1 != null) {
ps1.close();
ps1 = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
}
}
return update;

Write arraylist to a database java

I have two arraylists to insert into 2 columns in a database table as follows:
arraylist1: 123444, 324555, 6423643, 532326
arraylist2: jkfdsl, nkjfsdlj, jdslkfjdlkj, jfsldjfsk, fjdlskjfs
I wrote the following code to insert the arraylists but it is not working. I will appreciate your help.
try {
// Prepare a statement to insert a record
String sql = "INSERT INTO soundsdata.splog (arraylist1, arraylist2) VALUES(?,?)";
pstmt = (PreparedStatement) con.prepareStatement(sql);
pstmt.setArray(1,sptospring);
pstmt.setString(2,eachList.toString());
// Insert the row
pstmt.executeUpdate();
}finally {
pstmt.close();
}
Here's something that you can do:
Assuming that you're trying to create one row, where the 1st column will contain the content of the first ArrayList in comma-separated format and the 2nd column will contain the content of the secondArrayList
StringBuilder buffer = new StringBuilder();
boolean processedFirst = false;
String firstParam = null, secondParam = null;
try{
for(String record: arrayList1){
if(processedFirst)
buffer.append(",");
buffer.append(record);
processedFirst = true;
}
firstParam = buffer.toString();
}finally{
buffer = null;
}
processedFirst = false;
buffer = new StringBuilder();
try{
for(String record: arrayList2){
if(processedFirst)
buffer.append(",");
buffer.append(record);
processedFirst = true;
}
secondParam = buffer.toString();
}finally{
buffer = null;
}
secondParam = buffer.toString();
String sql = "INSERT INTO soundsdata.splog (arraylist1, arraylist2) VALUES(?,?)";
try{
psmt = (PreparedStatement) con.prepareStatement(sql);
pstmt.setString(1,firstParam);
pstmt.setString(2,secondParam);
pstmt.executeUpdate();
}finally {
pstmt.close();
}
You cannot store an ArrayList in a varchar column.
You need to store a string.
PreparedStatement ps = connection.prepareStatement(query);
for (Record record : arraylist1) {
int index=1;
ps.setString(index++,record.getItem());
ps.setString(index++,record.getItem2());
//
}
ps.executeBatch();
conn.commit();
Insert more than one record:
public String saveOrder(ArrayList<KIT0053MBean> insertList){
System.out.println("SaveOrder DAO Method is calling " +insertList.size());
Connection con=null;
PreparedStatement ps2=null;
try {
con=open();
con.setAutoCommit(false);
con.getTransactionIsolation();
ps2=con.prepareStatement(sql1);
Iterator<KIT0053MBean> it=insertList.iterator();
while(it.hasNext()){
KIT0053MBean order=(KIT0053MBean)it.next();
ps2.setString(1, model.getCustomerid());
ps2.setString(2, model.getSerialid());
ps2.addBatch();
}
int i[]=ps2.executeBatch();
System.out.println("###### insertion1### row "+i.length);
con.commit();
con.setAutoCommit(true);
} catch (Exception e)
{
System.out.println(e.getMessage());
}finally{
close(con);
close(ps2);
}
}
String[] stringArray = lists.toArray(new String[lists.size()]);
String string1 = stringArray[0];
String string2 = stringArray[1];
String string3 = stringArray[2];
String string4 = stringArray[3];
String string5 = stringArray[4];
// then write query for insert into database
insert into tablename values(string1 ......)

Can we use two queries using prepared statement in one method

Can we use two queries in one method while using prepared statement, I have tried using this but invalid column name exception is coming.
My code snippets is as follows.
public double getPayroll(){
ResultSet rs = null;
ResultSet rs2 = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getDBConnection();
int employeeId;
String q1 = "select e_salary,e_house_rent,e_conv_allow,e_id
from employee";
pstmt = conn.prepareStatement(q1);
rs = pstmt.executeQuery();
double dailyPay=0,basicPay=0,payroll2=0;
int houseRent=0,convAllow=0;
while (rs.next()) {
dailyPay = rs.getInt(1)*.03;
houseRent=rs.getInt(2);
convAllow=rs.getInt(3);
employeeId=rs.getInt(4);
}
String q2="select att_status from attendance where
e_id=employeeId";
pstmt = conn.prepareStatement(q2);
rs2 = pstmt.executeQuery();
int noOfPresents = 0;
while(rs2.next()){
noOfPresents+=1;
}
basicPay=dailyPay*noOfPresents;
payroll2+=basicPay+houseRent+convAllow;
return payroll2;
} catch (Exception e) {
e.printStackTrace();
return 0.0;
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Your problem is that the sql in q2 assumes that there is a column named employeeId, but I suspect you want to insert the value of the variable employeeId.
Change it to
select att_status from attendance where e_id=?
Then execute
pstmt.setString(1, employeeId);
before executing pstmt.executeQuery();

Categories

Resources