Writing a txt file to mySQL database - java

I'm currently trying to write a txt file to a mySQL database through a Java program. My database connects correctly through a JDBC driver and I can create tables etc through the program. However when I try to read the text file in I get this error message
java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''FName' , 'SName' , 'DOB') VALUES ('John' , 'McCullough' , '270696')' at line 1
I can't find an error in my SQL code. Here is the rest of the code from the class. Any help would be greatly appreciated.
try (Connection con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword)) {
FileReader file1 = new FileReader("resources/Test.txt");
BufferedReader buffer1 = new BufferedReader(file1);
String read;
while ((read = buffer1.readLine()) != null) {
String[] row = read.split(",");
String fName = row[0];
String sName = row[1];
String DOB = row[2];
String insert = "INSERT INTO chessleague.table1 ('FName' , 'SName' , 'DOB') VALUES ('" + fName + "' , '" + sName + "' , '" + DOB + "')";
ps = con.prepareStatement(insert);
ps.executeUpdate();
ps.close();
}
} catch (Exception ex) {
System.out.println(ex);
}

As mentioned in the comments, don't quote the column names.
The code heavily misuses prepared statements to execute simple SQL. The Connection Class has a createStatement() method that creates a simple statement which is meant for text form SQL commands.
Statement stmt = con.createStatement();
stmt.execute("SELECT * from test.t1");
Prepared statements expect a template that is used to create the SQL statements. Here's an example of how the insert could be done with prepared statement commands.
try (PreparedStatement ps = con.prepareStatement("INSERT INTO chessleague.table1 (FName , SName , DOB) VALUES (?, ?, ?)")) {
ps.setString(0, fName);
ps.setString(1, sName);
ps.setString(2, DOB);
ps.execute();
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
}

Related

how to insert into mysql database with java

i want to insert inputs i take from user into mysql database the connection is right but the insertion gives me error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near ''u_fname',
'u_lname', 'u_uname', 'u_pass', 'u_age', 'u_adderess') values('20','o'
at line 1
My code is:
public void adduser(User s) {
try {
sql = "insert into users ('u_fname', 'u_lname', 'u_uname', 'u_pass', 'u_age', 'u_adderess')"
+ "values('" + s.getFirstname() + "','" + s.getLastname()
+ "','" + s.getUsername() + "','" + s.getPassword() + "','" + s.getAge() + "','" + s.getAdderss() + "')";
stmt = conn.createStatement();
int i = stmt.executeUpdate(sql);
if (i > 0) {
System.out.println("ROW INSERTED");
} else {
System.out.println("ROW NOT INSERTED");
}
} catch (Exception e) {
System.out.println(e);
}
}
To insert into mysql, follow these steps-
Create a Java Connection to our example MySQL database. I believe you already took care of it. It will be something like this-
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 INSERT statement, using the Java PreparedStatement
syntax. Your PreparedStatement SQL statement will be as following this format-
String sql = " insert into users (first_name, last_name, date_created, is_admin, num_points)"
+ " values (?, ?, ?, ?, ?)";
Set the fields on our Java PreparedStatement object. It will done as-
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString (1, s.first_name);
preparedStmt.setString (2, s.last_name);
preparedStmt.setDate (3, s.date_created);
preparedStmt.setBoolean(4, s.is_admin);
preparedStmt.setInt (5, s.num_points);
Execute a Java PreparedStatement.
preparedStmt.execute();
Close our Java MYSQL database connection.
conn.close();
Catch any SQL exceptions that may come up during the process.
catch (Exception e)
{
System.err.println("Got an exception!");
// printStackTrace method
// prints line numbers + call stack
e.printStackTrace();
// Prints what exception has been thrown
System.out.println(e);
}

Add date from JXDatePicker into SQL Database in Netbeans

I would like to add a date value from JXDatePicker into my SQL database, however I'm getting this error when running it:
java.sql.sqldataexception: the syntax of the string representation of a datetime value is incorrect
This is my code:
try {
String url = "jdbc:derby://localhost:1527/Members";
String username = "admin1";
String password = "admin1";
Connection con = DriverManager.getConnection(url, username, password);
Statement stmt = con.createStatement();
String query = "INSERT INTO BOOKING(MEMBERID, NAME, CONTACT, "
+ "EMAILADDRESS, RESERVATIONDATE, RESERVATIONTIME) "
+ "VALUES('"+txtMemberID.getText()+"', '"+txtName.getText()+"', "
+ "'"+txtContact.getText()+"', '"+txtEmail.getText()+"', "
+ "'"+comboDate.getDate()+"', '"+comboTime.getSelectedItem()+"')";
stmt.execute(query);
JOptionPane.showMessageDialog(null, "Booking created");
txtMemberID.setText(null);
txtName.setText(null);
txtContact.setText(null);
txtEmail.setText(null);
comboDate.setDate(null);
comboTime.setSelectedItem("00");
}
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
The datatype specified for the Date attribute in my database is Date.
Thank you.
Your problem is that you're trying to embed a Date value (or a String representation of one) into the INSERT statement. Instead of concatenating variables into the query literal, you should use parameterized SQL through a PreparedStatement. In addition to protecting your code from SQL injection, parameterized statements are re-usable by the database, which means that the DB doesn't need to parse the SQL before each execution -- this is especially important if you're running a large number of queries in a loop.
Another thing that you should take care of, is closing the resources you've opened. In your example code, the Connection and Statement are left open after they are no longer needed. This is easy to fix using the try-with-resources statement, which was introduced in Java 7. The resources declared within the try clause get automatically closed after the statement is executed.
Putting it all together, here's an example of what the modified code could look like:
String query = "INSERT INTO BOOKING(MEMBERID, NAME, CONTACT, "
+ "EMAILADDRESS, RESERVATIONDATE, RESERVATIONTIME) "
+ "VALUES(?, ?, ?, ?, ?, ?)";
try (Connection con = DriverManager.getConnection(url, username, password);
PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, txtMemberID.getText());
ps.setString(2, txtName.getText());
ps.setString(3, txtContact.getText());
ps.setString(4, txtEmail.getText());
ps.setDate(5, new java.sql.Date(comboDate.getDate().getTime()));
ps.setString(6, comboTime.getSelectedItem().toString());
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "Booking created");
/*clear the UI components etc.*/
} catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString(), JOptionPane.ERROR_MESSAGE);
}

I need help selecting within a MySQL DateTime range in Java

I've got the following code in my app
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = " + userId +
" AND InsertTimestamp BETWEEN " + lastDate +
" AND " + DataProcessor.TODAY + " ORDER BY UserId, Occurred";
try{
if(null == conn)
openDatabaseConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery(); <------- this is the line which throws the SQL exception
retArray = this.getArrayListFromResultSet(rs);
}catch(SQLException sqle){
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
So when I run my app in the debugger, I get this exception message
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '00:00:00.0 AND 2014-08-20 00:00:00.0 ORDER BY UserId, Occurred' at line 1
I'm reasonably certain that there's simple and reasonable solution to this, but I have not been able to find it.
I've tried looking in the MySQL manual for a solution or a different format.
I've tried running my timestamps through a TIMESTAMP() functino and a DATE() function in the SQL, neither of which helped.
I pulled the fully formed SQL out of the Java code and ran it in MySQL Workbench with no issues, what-so-ever. So now I'm looking to the experts for help.
Dates in SQL must be enclosed within single quotes like strings.
As you're using a prepared statemtent, why you don't use '?' and stmt.setDate(...)?
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = ?" +
" AND InsertTimestamp BETWEEN ?" +
" AND ? ORDER BY UserId, Occurred";
try {
if(null == conn) {
openDatabaseConnection();
}
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, userId);
stmt.setDate(2, lastDate);
stmt.setDate(3, DataProcessor.TODAY);
ResultSet rs = stmt.executeQuery();
retArray = this.getArrayListFromResultSet(rs);
} catch(SQLException sqle) {
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
Anyway, I think you are setting the dates in the opposite order. You should put first 'today' then lastDate. Although I don't know your constraints...

quotation marks in string parameter insert statement

Hi I've been trying to insert a string into a sqlite database through java. but the string parameter I'm passing in the values sql statement has quotation marks in it as content. I'm thinking that is the error I'm getting why it isn't inserting into the database. is there a way to bypass the quotation marks in the insert statement. thank you.
this is the code:
public void addNote(String topicadd, String contentadd) throws Exception
{
try
{
getConnection();
statement = conn.createStatement();
statement.executeUpdate("insert into tbl_notes (notes_topic, notes_content) values ('" + topicadd + "', '" + contentadd +"')");
System.out.println("inserted note");
}
catch (Exception m)
{`enter code here`
System.out.println("error insert topic");
System.out.println(m.getMessage());
}
}
this is the parameter kind of long... this is all in contentadd
import java.sql.*;
Resultset rset = null; (this has no new ResultSet() initialization)
Connection conn = null; (this has no new initialization too...)
Statement statement = null; (this has now new initialization)
always.....
try
{
}
catch (Exception e) <- can switch e for any other alphabet
{
e.getMessage();
System.out.println("error this module"); <- personal practice
throw e;
}
- getting connection
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:m.db");
*** this is sqlite connection format 'm.db' is the database name
establish connection first..
statement syntax follows:
statement = conn.createStatement();
rset = statement.executeQuery("select * from tbl_notes");
- executeQuery is used for SELECT sql statements
rset = statement.executeUpdate("insert into tbl_notes (ID, status) values
('100', 'status here');
the whole text is in string contentadd, I'm making a short note-taking program... Well, it doesn't execute the insert statement... error somewhere near (word from text) on command prompt... I'm using sqlite... Please let me know if you need more detail. thank you again.
Use a PreparedStatement to insert values containing special characters:
getConnection();
PreparedStatement statement = conn.prepareStatement("insert into tbl_notes (notes_topic, notes_content) values (?, ?)");
statement.setString(1, topicadd);
statement.setString(2, contentadd);
statement.executeUpdate();
As you see you can use parameters with a PreparedStatement which can contain also quotation marks.
Also you get some protection against SQL injection because the Strings given to a PreparedStatement are escaped accordingly.

Java mysql syntax error

I get syntax error to mysql insert statement. May I know how to correct this error ?
user=txtuser.getText();
char[] pass=jPasswordField1.getPassword();
String passString=new String(pass);
try{
Connection con = createConnection();
Statement st = con.createStatement();
**String sql = "INSERT INTO login(username,Password)"+"VALUES"+"('"user"','"passString"')";**
st.executeUpdate(sql);
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Exception: "+ e.toString());
}
You're missing a few + operators:
String sql = "INSERT INTO login(username,Password) VALUES ('" + user + "','" + passString + "')";
Consider using PreparedStatement placeholders to set these parameters. This will protect you from SQL injection attacks also. Here is an example

Categories

Resources