Java mysql syntax error - java

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

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

Writing a txt file to mySQL database

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

PreparedStatement troubles in Java [duplicate]

This question already has answers here:
How to use a tablename variable for a java prepared statement insert [duplicate]
(4 answers)
Closed 7 years ago.
This is my method:
#Override
public void deleteOneRecord(String tableName, String id) throws ClassNotFoundException, SQLException{
// Validate the parameters here.
// String sql = "DELETE FROM " + tableName + " WHERE " + column + "=" + value;
String pKeyColumnName = "";
// Statement stmt = conn.createStatement();
DatabaseMetaData dmd = conn.getMetaData();
ResultSet rs = dmd.getPrimaryKeys(null, null, tableName);
while(rs.next()){
pKeyColumnName = rs.getString("COLUMN_NAME");
System.out.println("PK column name is " + pKeyColumnName);
}
//String sql = "delete from " + tableName + " where " + pKeyColumnName + "=" + id;
String sql2 = "delete from ? where ?=?";
PreparedStatement pstmt = conn.prepareStatement(sql2);
pstmt.setString(1, tableName);
pstmt.setString(2, pKeyColumnName);
pstmt.setInt(3, Integer.parseInt(id));
pstmt.executeUpdate();
}
This is my test main:
public static void main(String[] args) throws ClassNotFoundException, SQLException {
DBStrategy db = new MySqlDBStrategy();
db.openConnection("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/book", "root", "admin");
System.out.println(db.findAllRecords("author", 0).toString());
db.deleteOneRecord("author", "2");
System.out.println(db.findAllRecords("author", 0).toString());
db.closeConnection();
}
The db object works, open connection works, my find all records method works,
then my deleteOneRecord blows up. I get this error:
Exception in thread "main" 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 ''author' where 'author_id'=2' at line 1
Now my syntax hasn't changed, I was running this code as just a Statement no problem a few minutes ago, so I must be using PreparedStatement incorrectly somehow.
Any help would be appreciated greatly.
I don't believe you can use parameters for the table name or the column name. You'll have to concatenate those into the string. Depending on where they come from, be careful about SQL injection vulnerabilities!

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

JDBC does not Inserting data into mysql table

I have problem with inserting data into mysql table. JDBC doesnt inserting data into mysql table.
JDBC should get value from input "liczbaUzytkownikow" and "data from table form which contains informations about "termin" (Exactly: termin.nazwaObiektu, termin.adresObiektu, termin.dzien, termin.odKtorej and termin.doKtorej).
Here is code of this JDBC:
conn = ConnectionClass.Polacz();
ArrayList<Rezerwacja> rezerwacje = new ArrayList<Rezerwacja>();
PreparedStatement st = null;
ResultSet rs = null;
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
try
{
st = conn.prepareStatement(sql);
rs = st.executeQuery();
while(rs.next())
{
Rezerwacja rezerwacja = new Rezerwacja();
rezerwacja.setLiczbaUczestnikow(rs.getInt(1));
rezerwacja.setIdTermin(rs.getInt(2));
rezerwacje.add(rezerwacja);
}
}
catch(SQLException e)
{
System.out.println(e);
}
Any suggestions ?
You should use PreparedStatement to avoid sql injection attacks.
Furthermore your sql is wrong:
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
you cannot execute two different statements in a single batch.
In your case an Insert and an Update.
Create two PreparedStatement's:
String sql1 = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values (?,?)";
String sql2 = "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = ?";
PreparedStatement preparedStatement1 = con.prepareStatement(sql1);
preparedStatement1.setString(1, liczbaUczestnikow );
preparedStatement1.setInt(2, idTerminal);
PreparedStatement preparedStatement2 = con.prepareStatement(sql2);
preparedStatement2.setInt(1, idTerminal);
preparedStatement1.executeUpdate();
preparedStatement2.executeUpdate();

Categories

Resources