Java - how to insert data into data base from txt file - java

I am wondering how to read in a file and insert into a table in my data base. I written this:
String customerFile = "customer.txt";
Connection myConnect = ....
Statement mySt = myConnect.createStatement();
mySt.executeUpdate(..create customer table..);
int SSN;
String CNAME;
String GENDER;
int AGE;
String PROFESSION;
String line;
String[] tokens;
FileReader file1 = new FileReader(customerFile);
BufferedReader buffer1 = new BufferedReader(file1);
//throw away first line
line = buffer1.readLine();
//continue with rest of file
while((line = buffer1.readLine()) != null)
{
tokens = line.split(",");
SSN = Integer.parseInt(tokens[0]);
CNAME = tokens[1];
GENDER = tokens[2];
AGE = Integer.parseInt(tokens[3]);
PROFESSION = tokens[4];
String insertString = "insert into customer values ( " + SSN + ", " + CNAME + "," +
GENDER + ", " + AGE + ", " + PROFESSION +")";
mySt.executeUpdate(insertString);
}
I thought this was the right way to insert into a table. However, the issue I am having with is that the variables aren't being read in the right way.
Example rows:
3648993,Emily,male,63,Consulting
5022334,Barbara,male,26,Finance
With the example above, I would want to have a table with 2 rows and 5 columns but the code I put on top gave me an error when it reaches the name. I am not sure where the issue is.

You should replace insertString with
myConnect = getConnection();
myConnect.setAutoCommit(false);
File file = new File(fileName);
fis = new FileInputStream(file);
pstmt = myConnect.prepareStatement("insert into customer( " + SSN + ", " + CNAME + "," +
GENDER + ", " + AGE + ", " + PROFESSION +") values (?,?,?,?,?)");
pstmt.setString(1, SSN);
pstmt.setString(2, AGE);
....
pstmt.executeUpdate();
myConnect.commit();
Source : Insert text file into MySQL

Make sure you put quotes around string fields, so instead of:
String insertString = "insert into customer values ( " + SSN + ", " + CNAME + "," +
GENDER + ", " + AGE + ", " + PROFESSION +")";
do:
String insertString = "insert into customer values ( " + SSN + ", '" + CNAME + "','" +
GENDER + "', " + AGE + ", '" + PROFESSION +"')";

Normally I do such things in two steps:
1) create a java class representing just one row of the textfile. This class is instantiated with a line from the txt-file and this single row is parsed and the fields are created, so I have for every single field a getter and a setter having the right fieldtype. within this class I'm able to perform tests and corrective actions if a field is wrong or even empty.
2) I create a Writer-class that reads the textfile line by line and writes every single line into the db, mostly starting with the second line, because the first line contains the header. I strictly use PreparedStatement and use batchwriting, at the end, when file looping is finished, write the batch to the DB with PreparedStatement.executeBatch() and then I close down all DB-objects.

Related

Java resultSet getInt() returns no value

Here, resultSet.getInt() doesn't work, but I do not know what is wrong with my code.
I want to increment the value of the column (with the name as the variable 'attendance'). Using the SELECT statement I want to read the current value and by using UPDATE I want to increment the corresponding value by 1. But the problem is that int a = r.getInt("'" + attendance + "'"); doesn't work. It always returns the value 0 although the current value isn't 0 (e.g. 1). What is wrong with my code?
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:"+ x +".db");
s = c.createStatement();
r = s.executeQuery("SELECT '" + attendance + "' FROM viewer WHERE name = '" + name + "' AND year = '" + year + "'");
while (r.next()){
int a = r.getInt("'" + attendance + "'");
int b = 1 + a;
String sql = "UPDATE viewer SET '" + attendance + "' = ? WHERE name = ? AND year = ? ";
p = c.prepareStatement(sql);
p.setInt (1,b);
p.setString (2,name);
p.setInt (3,year);
p.executeUpdate();
}
p.close();
c.close();
// r.getInt() value always 0
}
catch (ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
Since you wrap the name of the column in single quotes, it is considered as the string literal 'attendance' and not the name of the column which is the value of the variable attendance.
Change to:
"SELECT " + attendance + " FROM viewer WHERE name = '" + name + "' AND year = '" + year + "'"
(why do you concatenate the arguments name and year? Use placeholders ? just like the UPDATE statement)
and
"UPDATE viewer SET " + attendance + " = ? WHERE name = ? AND year = ? "
and
int a = r.getInt(attendance);
since you only have 1 column, you can use column index, instead of column names
int a = r.getInt(0);

Using Java variables with Sikuli in Selenium-Webdriver

The code below is a Java code in Selenium Webdriver. The code reads a long list from an excel sheet. It stores the values in each excel cell in variables, LastName and FirstName. I need to use the variables in a query, after navigating to SQL Server management studio database. This is where am having issues. when I use the command 'screen.type(LastName);', the variable LastName throws "cannot be resolved to a variable" error.
How do I use the variables LastName and FirstName defined in Java in Sikuli.
File src = new File ("C:\\EmployeeList.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 = wb.getSheetAt(0);
int rowcount=sheet1.getLastRowNum();
System.out.println("Total Row is :" + rowcount);
for (int i=0; i<rowcount;i++) {
String LastName=sheet1.getRow(i).getCell(0).getStringCellValue();
String FirstName=sheet1.getRow(i).getCell(1).getStringCellValue();
System.out.println("Data Employee List is " +i+ " "+"is "+ LastName+ ", "+FirstName+");
}
wb.close();
//Navigated into SQL Server management studio database
screen.type(LastName);
LastName is declared in the for loop local scope, so it doesn't exist outside the for. You need to declare it outside
String lastName, firstName;
for (int i = 0 ; i < rowcount ; i++) {
lastName = sheet1.getRow(i).getCell(0).getStringCellValue();
firstName = sheet1.getRow(i).getCell(1).getStringCellValue();
System.out.println("Data Employee List is " + i + " " + "is " + lastName + ", " + firstName);
}
screen.type(lastName);
I'm not sure if this on purpose, but screen.type(lastName); will use only the last value of lastName. If you want to use all of them insert it into the loop. In that case you can leave the lastName declaration inside the for
for (int i = 0 ; i < rowcount ; i++) {
String lastName = sheet1.getRow(i).getCell(0).getStringCellValue();
String firstName = sheet1.getRow(i).getCell(1).getStringCellValue();
System.out.println("Data Employee List is " + i + " " + "is " + lastName + ", " + firstName);
screen.type(lastName);
}
By the way, variables in Java should start with lower case.

Sql query that outputs to ONE Joptionpane

String sql = "SELECT TOP 10 id, Trailer, Block, Location, Day, SetTime, Comment FROM TrailerLocation"
+ " ORDER BY id DESC";
rs = st.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String trailer = rs.getString("Trailer");
String block = rs.getString("Block");
String location = rs.getString("Location");
String date = rs.getString("Day");
String comment = rs.getString("Comment");
//Display values
JOptionPane.showMessageDialog(null,
"ID: " + id
+ ", Trailer: " + trailer
+ ", Block: " + block
+ ", Location: " + location
+ ", Date & Time: " + date
+ ", Comment: " + comment);
}
I want the Joptionpane to only display once with all the data not ten times.
You could move the JOptionPane.showMessageDialog(null, ... ) after the while loop.
And, in the while loop, add the informations you want in one unique string which you will display in you JOptionPane.
rs = st.executeQuery(sql);
StringBuilder str = new StringBuilder();
while(rs.next()){
//Retrieve by column name
str.append("ID: " + rs.getInt("id"));
str.append(", Trailer: " + rs.getString("Trailer"));
str.append(", Block: " + rs.getString("Block"));
str.append(", Location: " + rs.getString("Location"));
str.append(", Date: " + rs.getString("Day"));
str.append(", Comment: " + rs.getString("Comment"));
//new line
str.append("\n");
}
JOptionPane.showMessageDialog(null,str.toString());

ResultSet with variable

Ok so basically I have this code:
resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS");
writeResultSet(resultSet);
private void writeResultSet(ResultSet resultSet) throws SQLException {
System.out.println("jestem w writeresultset");
// resultSet is initialised before the first data set
while (resultSet.next()) {
// it is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g., resultSet.getSTring(2);
String id = resultSet.getString("id");
String user = resultSet.getString("IMIE");
String website = resultSet.getString("NAZWISKO");
String summary = resultSet.getString("ADRES");
String date = resultSet.getString("EMAIL");
String comment = resultSet.getString("TELEFON");
String opisso = resultSet.getString("OPIS");
JTextField myOutput = new JTextField(1600);
myOutput.setText("id w bazie danych to " + id + " imie to " + user
+ " nazwisko to " + website + " adres to " + summary + " email to "
+ date + " teelefon to " + comment + " opis to " + opisso);
add(myOutput);
}
}
What I want to achieve is this:
resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS
where NAZWISKO LIKE " variable );
writeResultSet(resultSet);
I want to search by variable which is already defined, however I'm stuck and have no idea how to do it like that.
Use PreparedStatement:
String nazwisko = ...
String query = "select * from FEEDBACK.COMMENTS where NAZWISKO LIKE ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, nazwisko);
ResultSet rs = pstmt.execute();
while (resultSet.next()) {
//...
}
In case you need to use a wildcard for your LIKE, choose one of these:
nazwisko = nazwisko + "%";
nazwisko = "%" + nazwisko;
nazwisko = "%" + nazwisko + "%";
up , there are alot weird errors with your code:
like cannot find symbol variable con or incompatible type boolean cannot be converted to resultset.
I have tried this: but there is an error when executing
preparedStatement = connect
.prepareStatement("select * from FEEDBACK.COMMENTS where NAZWISKO= ? ; ");
preparedStatement.setString(1, surname3);
while (resultSet.next()) {
String id = resultSet.getString("i
d");
String user = resultSet.getString("IMIE");
String website = resultSet.getString("NAZWISKO");
String summary = resultSet.getString("ADRES");
String date = resultSet.getString("EMAIL");
String comment = resultSet.getString("TELEFON");
String opisso = resultSet.getString("OPIS");
JTextField myOutput = new JTextField(1600);
myOutput.setText("id w bazie danych to " + id + " imie to " + user + " nazwisko to " + website + " adres to " + summary + " email to " + date + " teelefon to " + comment + " opis to " + opisso);
add(myOutput);
}
error:
the query went fine but , the error appears here "while (resultSet.next())"
SEVERE: null
java.lang.NullPointerException
at jdbcexample.Main.readDataBase(Main.java:416)
at jdbcexample.Main$7.mousePressed(Main.java:346)

CSV reading in java

Im having trouble reading from a CSV file
final String DELIMITER = ",";
Scanner fileScan = null;
Scanner dataSetScan = null;
String dataSet = null;
String sql = "";
File users = new File("user.txt");
String nickname = "";
String lastname = "";
String firstname = "";
String cartype = "";
String personimage = "";
String carimage = "";
int user_id = 0;
try {
fileScan = new Scanner(users);
} catch (Exception e) {
System.out.println(e);
}
while(fileScan.hasNext()){
dataSet = fileScan.nextLine();
dataSetScan = new Scanner(dataSet);
dataSetScan.useDelimiter(DELIMITER);
nickname = dataSetScan.next();
lastname = dataSetScan.next();
firstname = dataSetScan.next();
cartype = dataSetScan.next();
personimage = dataSetScan.next();
carimage = dataSetScan.next();
sql += "INSERT INTO users VALUES (";
sql += user_id++ + ", ";
sql += "'" + nickname + "', ";
sql += "'" + lastname + "', ";
sql += "'" + firstname + "', ";
sql += "'" + cartype + "', ";
sql += "'" + personimage + "', ";
sql += "'" + carimage + "' ";
sql += ");\n";
}
The above code wont work on the example file
alice,Wonder-Land,Alice,red Vauxhall Corsa,alice.jpg,alice_car.jpg
bob,Kett,Robert,,,
charlie,Carlos,Don,,,
However, it works just fine when there is a comma at the end of the line. (hvaing a comma here is not an option)
What can i do to make this work? It must be to do with my delimeter i think
Thank you
I wouldn't recommend using your own parser for CSV. CSV is surprisingly complex with little gotchas everywhere.
For instance, in CSV, it is legal to quote a column value with a comma in it
3 columns in this file
abc,"value1,value2",def
I recommend this library for java, it's very easy to use.
http://opencsv.sourceforge.net/
EDIT - May 2013
Since writing this post, I have switched to this library, which supports the CSV "standard" better and is actively developed.
http://supercsv.sourceforge.net/
Are you getting a NoSuchElementException from the following line?
carimage = dataSetScan.next();
If so you just need to wrap that with a hasNext check and perform a null check when you build your string.
if(dataSetScanner.hasNext()){
carimage = dataSetScan.next();
}
else{
carimage = null;
}
...
sql += carimage == null ? "NULL" : "'" + carimage + "' ";
I would recommend testing each token before inserting it,
But to answer your question, add an if condition before the last dataSetScan.next() call like so:
if (dataSetScan.hasNext()){
carimage = dataSetScan.next();
}

Categories