I keep getting an sql exception when I try to run this command although the fields in the data base are correct, same as email_chauffeur and password
public Chauffeur findChauffeurByEmailPwd(String email, String pwd) {
Chauffeur c = null;
try {
String req = "select * from chauffeur where email_chauffeur='" + email + "' and pwd='" + pwd + "'";
DataSource ds = DataSource.getInstance();
connection = ds.getConnection();
Statement s = connection.createStatement();
ResultSet rs = s.executeQuery(req);
if(rs.isBeforeFirst()){
rs.next();
c.setIdChauffeur(rs.getInt("id_chauffeur"));
c.setNomUser(rs.getString("nom_chauffeur"));
c.setPrenomUser(rs.getString("prenom_chauffeur"));
c.setCinUser(rs.getString("cin_chauffeur"));
c.setTelUser(rs.getInt("tel_chauffeur"));
c.setEmailUser(rs.getString("email_chauffeur"));
c.setPwdUser(rs.getString("pwd"));
c.setAdresseUser(rs.getString("adresse_chauffeur"));
c.setNote(rs.getInt("note_chauffeur"));
c.setNotifUser(rs.getInt("notif_chauffeur"));
}
} catch (SQLException ex) {
Logger.getLogger(ChauffeurDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return c;
}
The error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'email_chaffeur' in 'where clause'
You are running outdated compiled code. Delete all compiled .class files and force a rebuild.
As stated by the error message, the executed code is using a column named "email_chaffeur" but there's no such column in the database. It looks like you have a typo in your code.
My advice, fix the typo(s), redeploy the code.
You might also want to read about SQL injection and close the resources used (like Connection, etc)
Related
I'm trying to run a statement on the java main file and I'm able to connect to the data base, but not run the sql statement
my code is:
try {
System.out.println("Connecting to the database...");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Connected to database successfully");
System.out.println("Inserting");
stmt=conn.createStatement();
String sql="USE TheEmployeeDatabase" +
"SELECT * FROM EmployeeTable";
stmt.executeUpdate(sql);
System.out.println("worked");
} catch (SQLException e) {
e.printStackTrace();
}
and getting the error
You have an error in your SQL syntax
As long as the schema name TheEmployeeDatabase1 is part of your DB_URL, you don't need to have the USE TheEmployeeDatabase statement.
You statement should just be:
SELECT * FROM EmployeeTable
String sql="USE TheEmployeeDatabase " <--- you need whitespace here or you will have TheEmployeeDatabaseSELECT concatenated
So I am getting a database and my discord bot is connecting to the database but when I get it I am getting an error of com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'd1aa852e1a504d6cafbd55e0d2d28dea' in 'where clause'
Here is my code
int id = SQLUser.getIntFromDatabase("SELECT * FROM Players WHERE UUID = " + uuid.toString() + "", "ID");
if(id==-1) channel.sendMessage("ID is not valid please login to the WidowMC").queue();
else
{
Message messa = new MessageBuilder().append(Utils.getName(uuid) + " Skull").build();
channel.sendFile(Utils.getSkullFile(Utils.getName(uuid)), messa).queue();
channel.sendMessage("ID = " + id);
}
public static void excuteQuery(String query)
{
Connection conn = Core.getConnection();
try
{
Statement statement = conn.createStatement();
statement.executeQuery(query);
} catch (SQLException e)
{
e.printStackTrace();
}
}
You need to add quotes around the uuid to make it a literal, otherwise Mysql thinks you're referring to a column.
Also be very careful, your code is vulnerable to SQL injection, use the Prepared Stamements correctly could help you removing the vulnerability.
This is driving me mad because I cannot make any sense of it. I am executing the following code:
nameString = jcbClientList.getItemAt(jcbClientList.getSelectedIndex());
System.out.println(" Name String = " + nameString );
sql = "SELECT * FROM clients WHERE Name = \'" + nameString + "\'";
System.out.println(sql);
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while( rs.next()) {
clientID = rs.getInt(1);
}
}
catch(SQLException se) {
msg = "Problem getting client ID from DB \n" + se.getLocalizedMessage();
System.out.println(msg);
JOptionPane.showMessageDialog(null, msg);
}
The SQL string be built is correct. I have checked this by taking the System.out.println(sql) output of the string and pasting it into other code and it work perfectly. However, in this context I am getting an exception:
Invalid cursor state - no current row.
Even if I change the sql to be 'SELECT * FROM clients' which should return 20 rows and does elsewhere in the application, it still gives the same error. The database being addressed is an embedded Derby DB.
I seem to recall having run into specific JDBC drivers that did not properly implement the part that says " A ResultSet cursor is initially positioned before the first row ". I got around it by first doing a first() (or beforeFirst()) call and only then start invoking next().
i want to use database in my project, then i use this code for test( from jdbc tutorialspoint )
and change it for my code and db
then i get this error:
Creating statement...
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 'FROM test SET name=eee WHERE id=1' at line 1
Error: unable to connect to SQL!
java.sql.SQLException: 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 'FROM test SET name=eee WHERE id=1' at line 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1600)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1695)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3020)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2949)
at com.mysql.jdbc.Statement.execute(Statement.java:538)
at Test.main(Test.java:49)
my code:
import java.sql.*;
import java.math.*;
public class Test {
final static String DB_URL = "jdbc:mysql://localhost/testdb";
final static String USER = "root";
final static String PASS = "";
final static String JDBC_DRIVER="com.mysql.jdbc.Driver";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "UPDATE name FROM test SET name=eee WHERE id=1";
Boolean ret = stmt.execute(sql);
System.out.println("Return value is : " + ret.toString() );
int rows = stmt.executeUpdate(sql);
System.out.println("Rows impacted : " + rows );
sql = "SELECT id,name FROM test";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.print("ID: " + id);
System.out.print(", name: " + name);
}
rs.close();
stmt.close();
conn.close();
}
catch(ClassNotFoundException ex) {
ex.printStackTrace();
System.out.println("\n" + ex.getMessage());
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
catch(IllegalAccessException ex) {
ex.printStackTrace();
System.out.println("\n" + ex.getMessage());
System.out.println("Error: access problem while loading!");
System.exit(2);
}
catch(InstantiationException ex) {
ex.printStackTrace();
System.out.println("\n" + ex.getMessage());
System.out.println("Error: unable to instantiate driver!");
System.exit(3);
}
catch (SQLException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
System.out.println("\n" + ex.getMessage());
System.out.println("Error: unable to connect to SQL!");
System.exit(4);
}
}
}
my database is:
Picture of my DB
i see this page
but it doesn't help me!
At first your statement is not valid update statement. It has convention:
update <tableName> set <column> = '<newValue>';
This is the simpliest update statement. It will update all rows. Then you can add where clause to make selection of rows. Check this out.
Secondly, you are directly adding values for columns and aren't wrapping value(s) into single quotes (they has to be wrapped otherwise it won't work). To fix it you need to add single quotes like:
set name = 'value';
Sure, this works but i don't like this approach. It's very dangerous and unsafe. I suggest you to use parametrized statements which are much more safe (beware of SQL injection) and more human-readable.
Simple example of an usage of PreparedStatement:
String sql = "UPDATE test SET name = ? WHERE id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, <nameValue>); // binding value for name column
ps.setInt(2, <idValue>); // binding value for where clause
ps.executeUpdate(); // executes statement
I would like to mention a few main advantages of PreparedStatements:
They are precompiled, database-side caching of the SQL statement leads
to overall faster execution and the ability to reuse the same SQL
statement in batches.
Automatic prevention of SQL injection attacks by built-in escaping of
quotes and other special characters.
Eases setting of non-standard Java objects in a SQL (Date, Time,
Timestamp, BigDecimal, Blob, etc.)
This Query is not correct
String sql = "UPDATE name FROM test SET name=eee WHERE id=1";
modify it to
String sql = "UPDATE test SET name='eee' WHERE id=1";
Change String sql = "UPDATE name FROM test SET name=eee WHERE id=1"; to
String sql = "UPDATE test SET name='eee' WHERE id=1";
Another good option for constructing queries is to use "Prepared statements" - take a look at the oracle tutorial - link
It helps to avoid problem with quotes like in your case and provides greater sequrity. And as I remember it provides some preparation which help to execute queries faster.
replace:
String sql = "UPDATE name FROM test SET name=eee WHERE id=1";
on
String sql = "UPDATE name FROM test SET name='eee' WHERE id=1";
I am working on a web application using Java and MySQL.
I created a method that is supposed to return an ArrayList of the respective column name based on the various tables in the database.
However, when I debugged the method, I realised the while(rs.next()) causes an error. I used this site for reference, hence I am not sure what went wrong.
This is the code. Thanks.
// Returns the the all the columns in the table
public ArrayList getColumnName(String tableName) throws SQLException {
ResultSet rs = null;
List<String> columnName = new ArrayList<String>();
Statement st = null;
Connection con = null;
try {
// Get a connection from the connection factory
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/information_schema", "root", "xxxx");
// Create a Statement object so we can submit SQL statements to the driver
st = con.createStatement();
StringBuilder sql = new StringBuilder("SELECT column_name FROM information_schema.columns " +
"WHERE table_schema = 'testDB' AND table_name = '");
sql.append(tableName).append("'");
rs = st.executeQuery(sql.toString());
while (rs.next()) { // getting error..
columnName.add(rs.getString("column_name"));
}
} catch (SQLException ex) {
Logger.getLogger(ModificationPage.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (con != null || st != null) {
st.close();
con.close();
}
}
return (ArrayList) columnName;
}
According to the Javadoc of 1.6 (not sure which version of Java you're using):
Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
It's very, very unlikely that if you actually got to the line where rs.next() was called, that a database error occurred just then. So, the most likely result is that the result set was closed.
Please alter your code to the following and see if you still get the error on the same line:
while (!rs.isClosed() && rs.next()) { // getting error..
columnName.add(rs.getString("column_name"));
}
Also, Holy SQL Injection Attack, Batman!
Taking the raw string as you're doing and enclosing it within single quotes leads this code to have an SQL injection vulnerability. Basically all a malicious user has to do is end your query with a single quote (') and run a query of their own afterwards.
So, the exception never happens ?
A query error should be thrown at rs = st.executeQuery(sql.toString()) if that were the case, but if it make it to whileand didn't iterate, it's because of an empty resultset
Maybe you're passing wrong arguments to the query ?