I am trying check if a certain key exists in the database before i try to add a student whom might have the same key. I have a class called DataBaseHandler which has functions to manipulate the database, The studentAlreadyExist function returns true if the given id is present and false if not. When I try to run the application it gives me this 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
*******
Here is my code snippet for testing if a student exist
//check if the student exist
public boolean studentAlreadyExists(String id) throws SQLException{
//first connect to the database;
connectToDataBase();
selectSQL = "select name from student where idNumber like ?";
prstmt = con.prepareStatement(selectSQL);
prstmt.setString(1, id);
ResultSet rs = prstmt.executeQuery(selectSQL);
String dbname = null;
while(rs.next()){
dbname = rs.getString("name");
}
return dbname != null;
}
You've prepared it before, you don't have to deliver the queryString again as parameter.
API:
https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#executeQuery()
Should look like:
public boolean studentAlreadyExists(String id) throws SQLException{
connectToDataBase();
selectSQL = "select name from student where idNumber like ?";
prstmt = con.prepareStatement();
prstmt.setString(1, id);
/* Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.*/
ResultSet rs = prstmt.executeQuery();
String dbname = null;
while(rs.next()){
dbname = rs.getString("name");
}
return dbname != null;
}
Don't pass the selectSQL as a parameter (again) when you perform executeQuery.
Related
I have a database called 'airplane' inside which there is a table named booking.
The booking table has the columns phone(int type) ,name(text type),address(text type),city(text type) destination(text type),date(text type). I want to fetch only the rows whose phone column has value or data equal to phone number entered by the user . I wrote the following code for it . For context , I am using java using JDBC
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/airplane";
static final String USER = "root";
static final String PASS = "";
Connection conn = null;
try
{
System.out.println("enter cell no");
int cell=sc.nextInt();
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
// My SQL SELECT query.
String query = "SELECT * FROM `booking` where phone=cell";
// creating the java statement
Statement st = conn.createStatement();
/** executing the query, and getting a java resultset of all rows whose phone
column has the value equal to one entered by user and stored by me in
int variable cell**/
ResultSet rs = st.executeQuery(query);
//iterate through the java resultset
while (rs.next())
{
int Phone = rs.getInt("phone");
String Name = rs.getString("name");
String Address = rs.getString("address");
String City = rs.getString("city");
String Destination = rs.getString("destination");
String Date = rs.getString("date");
// print the results
System.out.format("%d, %s, %s, %s, %s, %s\n", Phone, Name, Address, City, Destination, Date);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
I am getting the error:
Got an exception!
Unknown column 'cell' in 'where clause'
What am I doing wrong?
Try this:
String query = "SELECT * FROM `booking` where phone=" + cell;
A better way to handle this is to use PreparedStatement
This case, the query would look like:
String query = "SELECT * FROM `booking` where phone=?"
and
statement.setInt(1, cell);
you will see it's gonna run
String query = "SELECT * FROM booking where phone="+"\"%s\"";
query=String.format(query,cell);
I'm trying to use prepared statements to set a table name to select data from, but I keep getting an error when I execute the query.
The error and sample code is displayed below.
[Microsoft][ODBC Microsoft Access Driver] Parameter 'Pa_RaM000' specified where a table name is required.
private String query1 = "SELECT plantID, edrman, plant, vaxnode FROM [?]"; //?=date
public Execute(String reportDate){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(Display.DB_MERC);
PreparedStatement st = conn.prepareStatement(query1);
st.setString(1, reportDate);
ResultSet rs = st.executeQuery();
Any thoughts on what might be causing this?
A table name can't be used as a parameter. It must be hard coded. So you can do something like:
private String query1 = "SELECT plantID, edrman, plant, vaxnode FROM [" + reportDate + "?]";
If you need a solution which is not vulnerable to SQL injection, you have to duplicate the query for all tables you need:
final static String QUERIES = {
"SELECT x FROM Table1 x WHERE a=:a AND b=:b AND ...",
"SELECT x FROM Table2 x WHERE a=:a AND b=:b AND ...",
"SELECT x FROM Table3 x WHERE a=:a AND b=:b AND ...",
...
};
And yes: the queries are duplicates and only the table name differs.
Now you simply select the query that fits your table, e.g. like
...
PreparedStatement st = conn.prepareStatement(QUERIES[index]);
...
You can use this approach wich JPA, Hibernate, whatever...
If you want a more verbose approach consider using an enum like
enum AQuery {
Table1("SELECT x FROM Table1 x WHERE a=:a AND b=:b AND ..."),
Table2("SELECT x FROM Table2 x WHERE a=:a AND b=:b AND ..."),
Table3("SELECT x FROM Table3 x WHERE a=:a AND b=:b AND ..."),
...
private final String query;
AQuery(final String query) {
this.query = query;
}
public String getQuery() {
return query;
}
}
Now use the either an index
String sql = AQuery.values()[index].getQuery();
PreparedStatement st = conn.prepareStatement(sql);
...
Or use a table name
String sql = AQuery.valueOf("Table1").getQuery();
PreparedStatement st = conn.prepareStatement(sql);
...
This is technically possible with a workaround, but very bad practice.
String sql = "IF ? = 99\n";
sql += "SELECT * FROM first_table\n";
sql += "ELSE\n";
sql += "SELECT * FROM second_table";
PreparedStatement ps = con.prepareStatement(sql);
And then when you want to select from first_table you set the parameter with
ps.setInt(1, 99);
Or if not, you set it to something else.
As a number of people have said, you can't use a statement parameter for a table name, only for variables as part of the condition.
Based on the fact you have a variable table name with (at least) two table names, perhaps it would be best to create a method which takes the entity you are storing and returns a prepared statement.
PreparedStatement p = createStatement(table);
You can't set table name in prepared statement
As said before, it is not possible to set the table name in a prepared statement with preparedStatement.setString(1, tableName). And it is also not possible to add parts of the SQL query to a prepared statement (eg preparedStatement.addSql(" or xyz is null")).
How to do it right without risking SQL injections?
The table name must be inserted into the SQL (or JQL) query you want to execute with string operations like "select * from " + tableName or String.format("select * from %s", tableName)
But how to avoid SQL injections?
If the table name does not come from user input, you are probably safe.
For example, if you make a decision like here
String tableName;
if(condition) {
tableName = "animal";
} else {
tableName = "plant";
}
final String sqlQuery = "delete from " + tableName;
...
If the table name depends on the users input, you need to check the input manually.
For example, with a white-list containing all valid table names:
if(!tableNamesWhitelist.contains(tableName)) {
throw new IllegalArgumentException(tableName + " is not a valid table name");
}
String sqlQuery = "delete from " + tableName;
or with an enum:
public enum Table {
ANIMAL("animal"),
PLANT("plant");
private sqlTableName;
private TableName(String sqlTableName) {
this.sqlTableName= sqlTableName;
}
public getSqlTableName() {
return sqlTableName;
}
}
and then convert the user-input string like ANIMAL into Table.ANIMAL. An exception is thrown, if no fitting enumeration value does exist.
eg
#DeleteMapping("/{table}")
public String deleteByEnum(#PathVariable("table") Table table) {
final String sqlQuery = "delete from " + table.getSqlTableName();
...
}
Of course these examples work with select, update, ... too and a lot of other implementations to check the user input are possible.
This might help:
public ResultSet getSomething(String tableName) {
PreparedStatement ps = conn.prepareStatement("select * from \`"+tableName+"\`");
ResultSet rs = ps.executeQuery();
}
I'm not sure you can use a PreparedStatement to specify the name of the table, just the value of some fields. Anyway, you could try the same query but, without the brackets:
"SELECT plantID, edrman, plant, vaxnode FROM ?"
String table="pass";
String st="select * from " + table + " ";
PreparedStatement ps=con.prepareStatement(st);
ResultSet rs = ps.executeQuery();
I am trying to connect to database in Java. It's a simple program.
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/servlets","root","");
smt = con.createStatement();
query = "select pass from users where uname = "+uname;
System.out.println(query);
rs = smt.executeQuery(query);
if((rs.getString("pass"))==pass){
out.println("correct pass...logged in..");
}
else {
out.println("Incorrect pass...not logged in..");
}
But it says
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 '#gmail.com'
at line 1
I am trying to verify the password for a particular email-id.
At this line
query = "select pass from users where uname = "+uname;
You have not quoted the uname, so if the value is name#gmail.com this results in a syntax error. I.e. the actual statement being sent to the DB is
select pass from users where uname = name#gmail.com
which is invalid. You should be using PreparedStatement instead
query = "select pass from users where uname = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
Replace this
query = "select pass from users where uname = "+uname;
to
query = "select pass from users where uname = "'+uname+'" ";
or try
query = "select pass from users where uname = ? ";
I am trying to create the table through java string but it is displaying error as table doesn't exist but when I run the same query directly on workbench it runs fine. Below is my code
String url = "jdbc:mysql://localhost:3306/" ;
String dbname = "tweetmap";
String username = "root";
String password = "root";
try
{
// SQL Driver needed for connecting to Database
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection(url+dbname,username,password);
c.setAutoCommit(true);
stmt = c.createStatement();
//Creating the Database if not Already Present
String sql = "CREATE TABLE if not exists senti "
+ "( latitude double NULL, "
+ "longitude double NULL, "
+ "Sentiment TEXT NULL) ";
stmt.executeUpdate(sql);
if(sentiment != null){
stmt1 = c.createStatement();
stmt1.executeUpdate("INSERT INTO `senti`(latitude,longitude,Sentiment) VALUE ('"+lati+"','"+longi+"','"+sentiment+"')");
}
}
catch(Exception e){
e.printStackTrace();
}
this is the problem stmt.executeUpdate(sql);
instead of executeUpdate use execute(String SQL) method.
execute(String SQL) is used for DDL/DML statement
while executeUpdate(String SQL) is used only for DML operation
Best way to execute any query in JDBC is using execute() method. This method can be used for any kind of query.
I hope below link will help you to understand more.
http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#execute(java.lang.String)
I have a mysql database that I am trying to retrieve from our website host (godaddy). I followed a format that seems to be right but it tells me that:
java.sql.SQLException: No database selected
Code:
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
// STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM item_master";
ResultSet rs = stmt.executeQuery(sql); //<-- This is where the error is.
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
// Display values
System.out.print("ID: " + id);
}
...
}
I did a print statement of the conn to maybe think the connection could of been null and was shown this:
com.mysql.jdbc.JDBC4Connection#2a6*****
Anyone have any ideas what could cause something like this?
Your URL for your database should include your database name. This is normally your URL followed by a "/DBNAME".
String URL = "jdbc:mysql://localhost:3306/mydb";
Where "mydb" is your database name.
What is the value of DB_URL? As far as I am aware, the URL needs to be of the form:
"WEBURL/DATABASENAME:PORT"
Are you just trying to connect to the WEBURL, without specifying a DATABASE?
I had the same problem.
Just run one more query (before your 'SELECT' statement) to connect to your database.
First:
sql = "USE <yourdatabase>";
ResultSet rs = stmt.executeQuery(sql);
And after:
sql = "SELECT * FROM item_master";
rs = stmt.executeQuery(sql);