Error while inserting into MYSQL database in JavaFX - java

I have a problem inserting data into MYSQL database. Using code below I get an error:
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 '?,?)' at line 1
CODE:
public void signUpUser(Connection conn, String userName, String password) {
String queryString = "INSERT INTO USERS (USER_ALIAS, USER_PASS) VALUES (?,?)";
try {
preparedStatement = (PreparedStatement) conn.prepareStatement(queryString);
preparedStatement.setString(1, userName);
preparedStatement.setString(2, password);
preparedStatement.executeUpdate(queryString);
} catch (SQLException e) {
e.printStackTrace();
}
}
But with this code the insert works normally:
public void signUpUser(Connection conn, String userName, String password) {
String queryString = "INSERT INTO USERS (USER_ALIAS, USER_PASS) VALUES ('"+userName+"', '"+password+"')";
try {
preparedStatement = (PreparedStatement) conn.prepareStatement(queryString);
preparedStatement.executeUpdate(queryString);
} catch (SQLException e) {
e.printStackTrace();
}
}
I want to know why does it throws error while using first part of code
Thank you in advance!

You are trying to execute update with the string although you have already created the statement.
You have to use:
preparedStatement.executeUpdate();

Related

java.sql.SQLSyntaxErrorException with Prepared Statements

I just started learning about MySQL and I am now trying to learn prepared statements. When I uses them, I get this error java.sql.SQLSyntaxErrorException. Can someone tell me where am I getting the syntax wrong? Thanks. Here is my code:
public class DBConnector {
private Statement statement;
private ResultSet result;
private PreparedStatement preparedStatement;
public void createDB() {
try {
sql = "CREATE DATABASE IF NOT EXISTS ?";
tableName = "test_name";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, tableName);
int myResult = preparedStatement.executeUpdate();
if(myResult == 1){
System.out.println("Database successfully created.");
}else{
System.out.println("Database with that name already exists. Please try again with different name.");
createDB();
}
}catch (SQLException e) {
System.out.println("Database creation failed.");
e.printStackTrace();
}
}
}
We can't bind Database names in Query parameters.
Statement stmt=con.createStatement();
int rs=stmt.executeUpdate("CREATE DATABASE dbname");
Try in this way, Database will create.

PreparedStatement won't send data over to database

I'm unsure as to why my program won't actually send the data supplied over to the table in my database table. I'm using a JavaFX application table to select a client from the table when selected and when signed in, the method sends the info to the DBconnect class to perform the operation.
Method to send the data to the DBconnect class:
public void signIn() throws SQLException {
BloomClient person = clientList.getSelectionModel().getSelectedItem();
dBconnect.sendToRoster(person.getFirstName(),person.getLastName());
}
Method to perform PreparedStatement:
public void sendToRoster(String fName, String lName) throws SQLException {
PreparedStatement st = c.prepareStatement("INSERT INTO sign_in_roster VALUES(?,?,?,?);");
c.setAutoCommit(false);
try {
st.setString(1,fName);
st.setString(2,lName);
st.setString(3, systemDate());
st.setString(4, systemTime());
c.commit();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
You've set all the bind variables, but you've forgot to execute the statement:
st.setString(1,fName);
st.setString(2,lName);
st.setString(3, systemDate());
st.setString(4, systemTime());
st.executeUpdate(); // Here
c.commit();

Getting Java mysql SQL Syntax error but my query seems normal

I am developing a simple java mysql based application and during data insertion into the database I'm getting an SQL error mentioned below.
Here is my code:
public DBConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase?useUnicode=true&useLegacyDatetimeCode=false&serverTimezone=Turkey", "root", "");
st = con.createStatement();
System.out.println("CONNECTED!");
} catch (Exception e) {
System.out.println("Error : " + e);
}
}
public void addCustomer(String name, String surname, String company, String adress, String adressTwo){
String addQuery = "insert into musteri (name,surname,company,adress,adressTwo) values (?,?,?,?,?)" ;
try {
st.executeUpdate(addQuery);
System.out.println("Data Added");
} catch (Exception e) {
System.out.println("Error occured when adding value to database : " + e );
}
}
Here is my java main method that add's the data:
public static void main(String[] args) {
// TODO code application logic here
Customers c1 = new Customers();
c1.setIsim("test");
c1.setSoyisim("test");
c1.setSirket("test");
c1.setAdres("test");
c1.setIletisim("test");
DBConnection db = new DBConnection();
db.addCustomer(c1.isim, c1.soyisim, c1.sirket, c1.adres, c1.iletisim);
}
The error I'm getting is:
Error occured when adding value to database : java.sql.SQLSyntaxErrorException: 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 ''insert into musteri (ad,soyad,sirket,adres,iletisim) values (?,?,?,?,?)'' at line 1
You are mixing statements with prepared statements. You should use a prepared statement and set the values to it:
public void addCustomer(String name, String surname, String company, String address, String adressTwo) {
String addQuery = "insert into musteri (name, surname, company, adress, adressTwo) values (?,?,?,?,?)" ;
// Shown here for simplicitly.
// The query could be prepared once and stored in a data member
try (PreparedStatement ps = con.prepareStatement(addQuery)) {
ps.setString(1, name);
ps.setString(2, surname);
ps.setString(3, company);
ps.setString(4, address);
ps.setString(5, addressTwo);
ps.executeUpdate();
System.out.println("Data Added");
} catch (Exception e) {
System.out.println("Error occured when adding value to database : " + e );
}
}
May I suggest you implement addCustomer like this. Use a local Statement and create it by using try-with-resource style and then set your parameters for the query
public void addCustomer(String name, String surname, String company, String adress, String adressTwo){
String addQuery = "insert into musteri (name,surname,company,adress,adressTwo) values (?,?,?,?,?)" ;
try (PreparedStatement stmt = con.prepareStatement(addQuery)) {
stmt.setString(1, name);
stmt.setString(2, surname);
stmt.setString(3, company);
stmt.setString(4, adress);
stmt.setString(5, adressTwo);
stmt.executeUpdate();
System.out.println("Data Added");
} catch (Exception e) {
System.out.println("Error occured when adding value to database : " + e );
}
}

I am trying to make a registration form with mysql in java and it gives me an error

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 '='Name'' at line 1
My code:
public void register(){
try {
String name="Name";
PreparedStatement updateSales = conn.prepareStatement(
"INSERT INTO users (name) VALUES (?)");
updateSales.setString(1, name);
updateSales.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}

Null pointer exception on insert into database java

Hi I have this method below which should insert values into my database. However I am getting a Null Pointer Exception on the PreparedStatement line
public void insertReservation(String name, String phone, int size, String date, String time, String additionalRequirements, String memberID, String themeID) throws SQLException, ClassNotFoundException {
try {
String strQuery = "INSERT INTO reservation VALUES (?, ? ,?, TO_DATE(?, 'dd-MMM-yy'), ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(strQuery);/
stmt.setString(1, name);
stmt.setString(2, phone);
stmt.setInt(3, size);
stmt.setString(4, date);
stmt.setString(5, time);
stmt.setString(6, additionalRequirements);
stmt.setString(7, memberID);
stmt.setString(8, themeID);
results = stmt.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}//end try
}
Am I inserting this correctly into my database? I am not sure why I am getting this null pointer exeception error.
conn is null, print its value.
Don't know but try this
String strQuery = "insert into reservation(ColumnName1, ColumnName2 ,ColumnName3,) values(?,?,?)";
and at the end it will be only execute();
like this stmt.execute();
executeQuery(); statement works with select query Only
Secondly have you described conn value in constructor or method in which ever class you are using the query if you have than assign it like this conn= SqlConnection.ConnecrDb();
below is the SqlConnection Seperate class i have created
public class SqlConnection {
Connection conn=null;
public static Connection ConnecrDb(){
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn= DriverManager.getConnection("jdbc:odbc:Test","","");
return conn;
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
Hope it will help you

Categories