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.
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 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();
I have a problem trying to execute more than one query into my Java Application code.
I have a procedure that is called in main and is in the class "Fant":
public void XXX(){
Connectivity con=new Connectivity(); // this class set up the data for the connection to db; if ( !con.connect() ) {
System.out.println("Error during connection.");
System.out.println( con.getError() );
System.exit(0);
}
ArrayList<User> blabla=new ArrayList<User>();
blabla=this.getAllUsers(con);
for (User u:blabla)
{
try {
Connectivity coni=new Connectivity();//start a new connection each time that i perform a query
Statement t;
t = coni.getDb().createStatement();
String query = "Select count(*) as rowcount from berebe.baraba";
ResultSet rs = t.executeQuery(query);
int numPrenotazioni=rs.getInt("rowcount");
rs.close(); //close resultset
t.close(); //close statement
coni.getDb().close(); //close connection
}
}
catch (SQLException e)
{
System.err.println("SQLState: " +
((SQLException)e).getSQLState());
System.err.println("Error Code: " +
((SQLException)e).getErrorCode());
}
}
}
The called function is defined as:
ArrayList<User> getAllUsers(Connectivity con) {
try{
ArrayList<User> userArrayList=new ArrayList<User>();
String query = "Select idUser,bubu,lala,sisi,gogo,gg from berebe.sasasa";
Statement t;
t = con.getDb().createStatement();
ResultSet rs = t.executeQuery(query);
while (rs.next())
{
User utente=new User(....); //user fields got from query
userArrayList.add(utente);
}
rs.close();
t.close();
con.disconnect(); //disconnect the connection
return userArrayList;
} catch (SQLException e) {
}
return null;
}
The main is:
public static void main(String[] argv) {
ArrayList<User> users=new ArrayList<User>();
System.out.println("-------- MySQL JDBC Connection Testing ------------");
Fant style = new Fant();
style.XXX();
}
The query performed into "getAllusers" is executed and into the arraylist "blabla" there are several users; the problem is that the second query that needs the count is never executed.
The MYSQlState given when running is= "S1000" and the SQLERROR is "0".
Probably i'm mistaking on connections issues but i'm not familiar with statements,connections,resultsets.
Thank you.
You might forget to call rs.next() before getting the result form it in XXX()methods as shown below:
ResultSet rs = t.executeQuery(query);
// call rs.next() first here
int numPrenotazioni=rs.getInt("rowcount");
I am designing a web-service using java and eclipse which returns the user details who are marked as customer in the database
I was successfully able to return details for a single user (as there was only one entry in the dB) with the following code:
public class GetData {
public LoginDetails getDetails(){
Connection conn;
Statement stmt;
ResultSet rs;
try {
LoginDetails lds=new LoginDetails();
Class.forName(driver);
conn=DriverManager.getConnection(url,username,password);
stmt=conn.createStatement();
String sql="select * from login where usertype='customer'";
rs=stmt.executeQuery(sql);
while(rs.next()){
lds.setUsername(rs.getString(1));
lds.setPassword(rs.getString(2));
lds.setUsertype(rs.getString(3));
lds.setActive(rs.getString(4));
}
return lds;
}
catch(ClassNotFoundException c){
c.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
What should I do if there are multiple values in dB matching the criteria and I want to display them all. Please advice.
Change your method signature to public LoginDetails[] getDetails()
And extend your while loop as follows:
Collection<LoginDetails> details = new ArrayList<LoginDetails>();
while(rs.next()){
LoginDetails lds=new LoginDetails();
lds.setUsername(rs.getString(1));
lds.setPassword(rs.getString(2));
lds.setUsertype(rs.getString(3));
lds.setActive(rs.getString(4));
details.add(lds);
}
return details.toArray(new LoginDetails[0]);
Return an collection type suggestively java.util.List , preferably ArrayList from the method.