SQL WHERE not working with Discord - java

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.

Related

Java JDBC Derby Syntax Error

Hi I have a problem with my syntax in my java code. I have a tableview which gets its data from a SQL database. I have created 3 tables in the database book, customer, order. When I click a button I want to take the selected books and add them to the order table.
Here is the code from the main program (calling the method from db):
if(table.getSelectionModel().getSelectedItems().iterator().hasNext()) {
db.insertOrder(new Bestellung(customerid,table.getSelectionModel().getSelectedItems().iterator().next()));
The table book is fixed. Just the two other tables customer,order are dynamic.
The problem:
I create the values in the order table like this
String ct = "CREATE TABLE Order (" + "Order_Id integer generated always as identity, " + "CUSTOMER_ID BIGINT" + "ISBN, CHAR(13) " + "PRIMARY KEY(Order_Id))";
and so on...
I insert into order table like this. (Here is the syntax problem in the String i That's the position where the compiler says it doesn't work..)
String i = "INSERT INTO ORDER(CUSTOMER_ID,ISBN), VALUES(?,?)";
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DriverManager.getConnection(connString);
stmt = conn.prepareStatement(i);
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
stmt.setLong(1, order.getCustomerId());
stmt.setString(2, order.getBuch().getISBN());
stmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
finally {
try {
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
and here is the syntax error which I got
Syntax error: Encountered "ORDER" at line 1, column 13.
So how do I have to correct my syntax in the string i? Does anyone have any ideas?
INSERT INTO ORDER(CUSTOMER_ID,ISBN), VALUES(?,?)
^
The comma is superfluous. Also, in your CREATE TABLE
... + "ISBN, CHAR(13) " + ...
^
This comma is also extraneous.
If you want to use reserved words/keywords as Table name, you should:
MySQL: use ' , like : select * from 'Order'
Oracle, PostgreSQL: use " , like : select * from "Order"
But it is bad practice, try to change your table name.
You have another Error that answered by #Jim Garrison.

H2 Embedded Database tables not shown in Intellij Database Client

I'm learning how to implement a database into a music player application, and decided to use the embedded H2 database for my implementation.
public class H2EmbeddedDB {
public H2EmbeddedDB() {
try {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:~/data/musicAppDB", "sa", "");
Statement st = conn.createStatement();
/*
String createTableSQL = "CREATE TABLE PLAYLISTS " +
"(playlistID INTEGER not NULL, " +
" playlistName VARCHAR(255), " +
" musicToContinuePath VARCHAR(255), " +
" durationToContinue INTEGER)";
st.execute(createTableSQL);
*/
String sql = "INSERT INTO PLAYLISTS " + "VALUES (123456789, 'Zara', 'C:\\Music', 18)";
st.executeUpdate(sql);
ResultSet rs;
rs = st.executeQuery("select * from playlists");
while (rs.next()) {
System.out.println(rs.getString("playlistName"));
}
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Just a simple test class, I commented out the create table after the table is created. Everything works fine, the application prints out 'Zara' like it should, but I cannot find the table in the Intellij Database Tool.
[How I'm importing the database]
https://i.gyazo.com/e2c1360729d53f837ffe3195290db7fa.png
[Not showing anything in the DB]
https://gyazo.com/4ddc9cea065bd928471aff0805130f73
I know where it is storing the database, it's in my user folder/data, and I've tried putting the absolute path to it when connecting with intellij client. The connection test succeeds as well.

java SQLquery Error

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)

jdbc Error, unable to connect to sql

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";

H2: Error on all other computers

I'm using the H2 database in my Java project (embedded mode).
On my computer at home everything works, the connection can be established, but on all other computers I always receive the following error:
org.h2.jdbc.JdbcSQLException: Table "CUSTOMERS" not found; SQL
statement: SELECT * FROM CUSTOMERS [42102-162]
I'm sure, that within the DB everything is alright, it should be something with the connection.
But even if I import the h2-1.3.162.jar file, the error still remains.
String dbClass = "org.h2.Driver";
String dbDriver = "jdbc:h2:~/cc";
String user = "user1";
String pass = "test1";
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public void connect() {
boolean done = false;
//load driver
try {
Class.forName(dbClass).newInstance();
System.out.println("driver loaded"); // This is shown in the Compiler
} catch (Exception ex) {
System.out.println("error while loading driver");
System.err.println(ex);
}
// Connection
try {
conn = DriverManager.getConnection(dbDriver, user, pass);
System.out.println("connected"); // This is shown in the Compiler
done = true;
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
public Vector select() {
data = new Vector();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM CUSTOMERS");
while (rs.next()) {
Vector row = new Vector();
row.add(rs.getInt("id"));
row.add(rs.getString("fname"));
row.add(rs.getString("lname"));
row.add(rs.getString("street"));
row.add(rs.getString("city"));
row.add(rs.getString("zip"));
row.add(rs.getString("state"));
row.add(rs.getString("phone"));
row.add(rs.getString("birthday"));
row.add(rs.getString("email"));
row.add(rs.getInt("code"));
data.add(row);
}
rs.close();
stmt.close();
} catch (SQLException ex) {
System.out.println("error while selecting"); // I receive this error
System.err.println(ex);
}
return data;
}
The problem isn't with your connection as you'd receive an exception well before then if it was failing to connect to the database. The exception is pretty clear about what the issue is, as well - it can't find the CUSTOMERS table. That could be because the table doesn't exist at all, or the connection is pointing at the wrong database; try putting in the full schema information of the table, rather than just its name, and see if that works.
I'm sure, that within the DB everything is alright, it should be
something with the connection. But even if I import the h2-1.3.162.jar
file, the error still remains.
Check your assumptions. This one is incorrect.
There's nothing in the message to suggest that you couldn't connect. Either you connected to the wrong database OR the one you did connect to didn't CREATE TABLE CUSTOMERS. (Should be named CUSTOMER, not plural.)
You'll fix your error faster if you stop assuming that everything you did is correct. You should be assuming that everything is wrong.
I'd print the stack trace when you catch that exception. It'll give you more information.
Finally I figured it out!
It had nothing to do with my tables, the database couldn't be found. When trying to connect to a database which can't be found with String dbDriver = "jdbc:h2:~/cc";, a new database with the name cc (in my case) will be created (of course an empty one with no tables) and the connection is established. That's why I haven't received any connection errors.
In the next step I tried to retrieve some data from the new created empty database and therefore received the error, that my table doesn't exist.
So I changed this line: String dbDriver = "jdbc:h2:file:lib/cc"; and copied into the lib directory of my application my old database cc.h2.db.
That's all!
PS: Here is a similiar problem: h2 (embedded mode ) database files problem

Categories