Im trying to check if a entry is set, so for example in a row with: user, password, birth
I check if in column user f.e. "mxrlin" is
For that im using that code in my Main Class:
if(!mySQL.isSet(tableName, "houseNumber", houseNumberStr)){
System.out.println(house.getHouseNumber() + " not set yet");
inserts.add(new BetterMySQL.KeyValue("houseNumber", houseNumberStr));
mySQL.insertEntry(tableName, inserts);
}else {
System.out.println(house.getHouseNumber() + " set -> updating");
mySQL.update(tableName, inserts, "houseNumber", houseNumberStr);
}
And the mySQL.isSet() method looks like this:
public boolean isSet(String tableName, String key, String value){
Check.checkNotEmpty(tableName);
Check.checkNotEmpty(key);
Check.checkNotEmpty(value);
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE ?=?", Arrays.asList(key, value));
try {
if(resultSet.next()){
return resultSet.getObject(value) != null;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
But with this code it always debugs me "house.getHouseNumber() + " not set yet", so the Class doesnt find the entry that is set
You can't bind a parameter to a column name. The key in this case will be treated as a string literal in SQL.
Assuming a method call like this:
mySQL.isSet("houses", "houseNumber", "2335")
this code:
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE ?=?", Arrays.asList(key, value));
Will generate a SQL statement equivalent to
SELECT * FROM houses WHERE 'houseNumber'='2335'
Of course, the string 'houseNumber' will never equal the string '2335', so no results will be returned.
You'll need to substitute key into the SQL string, just like tableName already is:
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE " + key + "=?", Arrays.asList(value));
Related
I'm trying to create a table with a list of names in it. This outputs:
"Failed to create table_name"
It was working before, I'm using Netbeans IDE with SQLite 3.7.2. I've also tried executing statements on the database which works fine. But it won't work through the Java code below
class DatabaseHelper{
public void addToDb(String tbname, List<String> name){
try {
String url = "jdbc:sqlite:D:/names.db";
Class.forName("org.sqlite.JDBC");
try(Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();){
stmt.execute("CREATE TABLE IF NOT EXISTS " + tbname + "(id integer PRIMARY KEY AUTOINCREMENT,"
+ "name text NOT NULL)");
name.forEach((s) -> {
try{
stmt.execute("INSERT INTO " + tbname + "(name) VALUES('" + s + "')");
}catch(SQLException e){
e.printStackTrace();
}
});
System.out.println("Finished");
}catch(SQLException e){
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
EDIT : It does works, only takes to refresh it. No actual problems it seems
Try to create your table with a database name like this :
String query = "CREATE TABLE IF NOT EXISTS databasename." + tbname +
" (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL)";
If your database already contain schema then create your table with schema name like this :
CREATE TABLE [IF NOT EXISTS] [schema_name].table_name (
so :
String query = "CREATE TABLE IF NOT EXISTS sch_name." + tbname +
" (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL)";
You can learn more here : SQLite Create Table
Ooops this is logic
This error is logic it return false all the time, if you try st.executeUpdate(q) and your query is success it will return 0 because CREATE TABLE does not return any thing for that you get negative result all the time, not like Insert or Update it return a result when you execute your statement, so i suggest to change your code to this :
boolean created;
try {
q = "CREATE TABLE ...";
Statement st = connection.createStatement();
//you can use
System.out.println(st.executeUpdate(q));
//or
System.out.println(st.execute(q));
created = true;
} catch (SQLException e) {
created = false;
}
//now you can check if your table is created or not
if(created){
System.out.println("Table created with sucess");
}else{
System.out.println("Faild to create table");
}
Hope this work with you.
if(stmt.execute("CREATE TABLE IF NOT EXISTS " + tbname + ";"+"CREATE TABLE "+ tbname + "(id integer PRIMARY KEY AUTOINCREMENT,"
+ "name text NOT NULL)"))
or can you give the exception that was raised
I am trying to complete my Java Code to execute a SELECT Query that will write the Results into Sysout.
Here is my Code:
public void PullFromDB() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
String sql = "SELECT * FROM " + Name + ";";
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
Integer ID = rs.getInt("id");
System.out.println("ID = " + ID.toString());
String entry = rs.getString(Properties.get(j));
System.out.println(Properties.get(j) + "=" + entry);
j++;
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
When I sysout my SQL Query it looks like this:
CREATE TABLE IF NOT EXISTS Cars(ID INTEGER PRIMARY KEY AUTOINCREMENT,AnzSitze TEXT,Marke TEXT,Pferdestärke TEXT);
INSERT INTO Cars(AnzSitze,Marke,Pferdestärke) VALUES('vier','Audi','420');
SELECT * FROM Cars;
Those are just some examples I put in.
maybe create and propabley insert has failed, i see none-ascii characters in filed name Pferdestärke try to use valid names
check this
Permitted characters in unquoted identifiers:
ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar,
underscore)
Extended: U+0080 .. U+FFFF
so replace the filed name Pferdestärke to Pferdestarke in all qrys and try again
I am trying to check if the players name and the invited players name that already exists in the database, I try this:
public boolean isFriends(ProxiedPlayer inviter, ProxiedPlayer invited) {
try {
Statement sql = mySql.getConnection().createStatement();
ResultSet resultSet = sql.executeQuery("SELECT * FROM `friends` WHERE `friendinviter`='" + inviter.getName() + "'`invitedfriend`='" + invited + "';");
ProxyServer.getInstance().broadcast("1");
if(resultSet.next()) {
sql.close();
resultSet.close();
return true;
}
sql.close();
resultSet.close();
return false;
}catch (SQLException e) {
e.printStackTrace();
return false;
}
}
I tried debugging it by trying to get what it returns in the result-set but the code never came so far.
My first suggestion is you should use PreparedStatement for this portion of code.
Secondly in the line "SELECT * FROM friends WHERE friendinviter='" + inviter.getName() + "'invitedfriend='" + invited + "';" the portion "'invitedfriend='" + invited I think requires a VARCHAR to be passed as parameters but you are passing an instance of ProxiedPlayer. So the corrected code should be:
"SELECT * FROM `friends` WHERE ` friendinviter`='" + inviter.getName() + "'`invitedfriend`='" + invited.getName() + "';"
You have a syntax error in:
ResultSet resultSet = sql.executeQuery("SELECT * FROM `friends` WHERE `friendinviter`='" + inviter.getName() + "' and `invitedfriend`='" + invited + "';");
You miss the logical operator in your where clues.
You should learn about prepared statements.
I'm doing an app for school project and I came across this error I've tried to figure it out but I can't seem to fix it.
Let me explain the problem first, basically I'm trying to update previously created user. Initially the profile has only username and a password. I want the user to be able to add whatever details he wishes to later on once he has created his own profile.
I have one class which has the database connectivity and update Profile method. The other class is a jFrame where user can input some data into textfields and the intention is that it will be inserted into fields for existing profile within the database (Initially those fields are declared as null).
Below you can see my DBConnect class which contain the Login method and UpdateProfile method. In the login method I'm creating a profile object which holds all the variables and methods such as getUsername, getPassword etc.
public class DBConnect {
private Connection dbConnection;
public Profile profile;
public DBConnect() {
try {
dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/prototype?user=root");
} catch (Exception ex) {
System.out.println("Connection failed :" + ex);
}
}
public void Login() {
profile = new Profile(LoginWindow.usernameField.getText(), LoginWindow.passwordField.getText());
Statement userQuery = null;
try {
//Look for the user with valid username and password
userQuery = dbConnection.createStatement();
ResultSet rs = userQuery.executeQuery("Select * FROM Profile WHERE pName = \"" + profile.getUsername() + "\" and password = \"" + profile.getPassword() + "\"");
if (rs.next()) {
profile.isLoggedin(true);
} else {
profile.isLoggedin(false);
}
} catch (SQLException ex) {
profile.isLoggedin(false);
System.out.println(ex);
} finally {
try {
if (userQuery != null) {
userQuery.close();
}
} catch (SQLException ex) {
System.out.println("Failed to close login query");
}
}
}
public void updateProfile(String _height, String _weight, String _goalWeight, String _age) {
Statement updateQuery = null;
try {
updateQuery = dbConnection.createStatement();
updateQuery.executeUpdate("UPDATE Profile SET height='" + _height + "',weight='" + _weight + "',goalWeight='" + _goalWeight + "',age='" + _age + "' WHERE pName =" + profile.getUsername());
} catch (SQLException ex) {
System.out.println(ex);
} finally {
try {
if (updateQuery != null) {
updateQuery.close();
}
} catch (SQLException ex) {
System.out.println("Failed to close updateCustomer query");
}
}
}
}
I'm trying to update some of the fields that were empty with the Update Profile method and to get the profile that I want to update I wrote "WHERE pName =" + profile.getUsername());" in order to retrieve the record of the user.
Finally in the EditProfile jFrame I wrote this method to pass on the parameters for the updateProfile methods.
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {
LoginWindow.dbc.updateProfile(heightTextField.getText(), weightTextField.getText(), goalWeightTextField.getText(), ageTextField.getText());
}
Everything compiles but I'm having mySQLSyntaxError which is:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'Admin' in 'where clause'
The database is not updated and I don't know how to fix it.
My assumptions is that there is a problem with "WHERE pName =" + profile.getUsername());" in updateProfile declaration. The "Admin" is the result of profile.getUsername(); and its the actual username of currently logged in user.
Please help.
You have a little syntax error: Your line
updateQuery.executeUpdate("UPDATE Profile SET height='" + _height + "',weight='" + _weight + "',goalWeight='" + _goalWeight + "',age='" + _age + "' WHERE pName =" + profile.getUsername());
should read
updateQuery.executeUpdate("UPDATE Profile SET height='" + _height + "',weight='" + _weight + "',goalWeight='" + _goalWeight + "',age='" + _age + "' WHERE pName ='" + profile.getUsername()) + "'";
(You need to enclose the pName parameter with single quotes.)
...and you really need to start using PreparedStatement as others also suggested.
that exactly the problem. try that:
ResultSet rs = userQuery.executeQuery("Select * FROM Profile WHERE pName = '" + profile.getUsername() + "' and password = '" + profile.getPassword() + "' ");
I have a SQL query, consisting of different statements (this is a simplified version, which also triggers the error) :
private static String getActiveKeyEventsSql =
"SET #report_model_id = 2; " +
"SELECT MAX(report_ts) AS report_ts " +
"FROM `pulse_data`.`key_event_reports` " +
"WHERE report_model_id = #report_model_id ";
I am trying to call that statement from inside my Java Application:
public static void main(String[] args) throws Exception {
MySQLLayer _db = new MySQLLayer();
Connection _conn = null;
try {
_conn = _db.getConnection();
PreparedStatement getActiveKeyEventsStmt = _conn.prepareStatement(getActiveKeyEventsSql);
ResultSet rs = getActiveKeyEventsStmt.executeQuery();
while (rs.next()) {
LOG.info(rs.getLong("report_ts"));
}
} catch (SQLException e) {
LOG.error("COULD NOT GET MAX REPORT.", e);
} finally {
try {
if (_conn != null && !_conn.isClosed()) {
_conn.close();
}
} catch (SQLException e) {
LOG.info("COULD NOT CLOSE CONNECTION.", e);
}
}
}
But it triggers the following error:
java.sql.SQLException: ResultSet is from UPDATE. No Data.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6870)
at com.stockpulse.stockstorm.sentiment.JavaTest.main(JavaTest.java:36)
In other places of my application, this schema works just fine. When I copy this statement to the MySQL console, it works just fine.
Here is the String to init the DB:
config.setJdbcUrl(
"jdbc:mysql://" + cred.getHOST() + "/" + cred.getDB()
+ "?allowMultiQueries=true&characterEncoding=utf-8&useUnicode=true&rewriteBatchedStatements=true&relaxAutoCommit=true"
);
Why is JDBC behaving this way out of the sudden?
Try breaking your statement into
a = "SET #report_model_id = 2; ";
b = "SELECT MAX(report_ts) AS report_ts " +
"FROM `pulse_data`.`key_event_reports` " +
"WHERE report_model_id = #report_model_id ";
And do PreparedStatement.addBatch() for each.