Populating database via jdbc
In the below code, values are inserted manually: 13 and Aman. But what I am doing is reading a file and then till the completion of the file, I am inserting values from it into mysql database tables.
public class Main {
public static void main(String[] argv) throws Exception {
Strin开发者_开发技巧g driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial", "root", "root");
Statement st = con.createStatement();
int val = st.executeUpdate("INSERT employee VALUES(" + 13 + "," + "'Aman'" + ")");
System.out.println("1 row affected");
}
}
I was trying to use each line like this:
String query = "INSERT INTO home (home_no, arrival_time, duration, persons, price, origin_city) VALUES("+line+");";
How do I do it?
Depending on how large the contents of the file that you are reading, it may be worth while to check LOAD DATA INFILE
syntax, rather than executing queries in a for
or while
loop.
Edit:
Without seeing your code and line
is the current line of the file you are reading and that you are using the syntax above to store the query
, I would break down your problems,
- Check the
line
variable prior to executing the query - Check how to insert the values manually opposed to reading the contents of the file, as you had shown above with
13
andAman
. - Figure out how to piece those two together, may need string manipulation.
This should be all you need.
BufferedReader rd = new BufferedReader(new FileReader("yourFile.txt"));
String line;
while ((line = rd.readLine()) != null)
{
// This time this loop runs, you will have the next time of your file.
insertARecord(line.split(" "));
}
rd.close();
// A bit further
public void insertARecord(String[] data)
{
// insert your record.
}
精彩评论