I'm trying to update record in mysql database using java.
This is my code:
Statement stmt = con.createStatement();
String sql = "";
JOptionPane.showMessageDialog(null, "test");
sql = "update users set email='" + email1.getText() + "' WHERE fullname='" + user1 + "'";
stmt.executeUpdate(sql);
stmt.close();
con.close();
I'm getting this error:
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: No operations allowed after statement closed.
Related
I'm currently working on a project where we have an inventory for an optical lens company which is stored in a database. I've connected my database to my java program and im just having an issue selecting a row based on a column value. Im doing this by
String name=lookUpName.getText();
try (
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/productitem?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC",
"root", "123456789"); // for MySQL only
Statement stmt = conn.createStatement();
) {
String strSelect = "select * from products where productName= "+name+"";
System.out.println("The SQL statement is: " + strSelect + "\n"); // Echo For debugging
ResultSet rset = stmt.executeQuery(strSelect);
}
rset.close();
when it tries to execute the query it gives me an error. but if i run a regular query using the sql console like select *
from products where productName='golden vintage'; it works. can someone help me with the java part.
the debugging output i have in there shows
The SQL statement is: select * from products where productName= golden vintage
The error I get is:
java.sql.SQLSyntaxErrorException: 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 'vintage' at line 1
I figured it out using the Prepared Statements
String strSelect = "select * from products where productName= ?";
PreparedStatement st = conn.prepareStatement(strSelect);
st.setString(1,name);
ResultSet rs = st.executeQuery();
while (rs.next()) {
String productid = rs.getString(1);
String productColors=rs.getString(2);
String productPrices = rs.getString(3);
String productBrands=rs.getString(4);
String productStyles = rs.getString(5);
String productNames=rs.getString(6);
System.out.println(productid +" "+productNames + " " +productBrands + " " + productStyles + " " + productColors + " " + productPrices);
}
I am using this query
sql=String.format("INSERT INTO PM_AM_ASSET_AUDIT(TAG_ID,MODEL_ID,CATEGORY_ID,DESCRIPTION,NOTES,STATUS_ID,PARK_ID,TOWER_ID,FLOOR_ID,UNIT_ID,CUSTOMER_ID,CHECK_OUT_DATE,DUE_DATE,MODIFIED_BY,MODIFIED_DATE,REVISION,PARK_NAME,TOWER_NAME,FLOOR_NAME,UNIT_NAME,CUSTOMER_NAME)
SELECT TAG_ID,MODEL_ID,CATEGORY_ID,DESCRIPTION,NOTES,STATUS_ID,PARK_ID,TOWER_ID,FLOOR_ID,UNIT_ID,CUSTOMER_ID,CHECK_OUT_DATE,DUE_DATE,MODIFIED_BY,MODIFIED_DATE,REVISION,PARK_NAME,TOWER_NAME,FLOOR_NAME,UNIT_NAME,CUSTOMER_NAME
FROM PM_AM_ASSET_MASTER where id ="+id);
preparedStatement = connection.prepareStatement(sql,new String[] {"ID"});
but, I got this exception
java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended
When I remove generated keys concept the query executes.
Newer use concatenation in your statements to prevent sql injection.
Try this case:
String sql = "INSERT INTO PM_AM_ASSET_AUDIT " +
" (TAG_ID,MODEL_ID,CATEGORY_ID,DESCRIPTION,NOTES,STATUS_ID,PARK_ID,TOWER_ID,FLOOR_ID,UNIT_ID,CUSTOMER_ID,CHECK_OUT_DATE,DUE_DATE,MODIFIED_BY,MODIFIED_DATE,REVISION,PARK_NAME,TOWER_NAME,FLOOR_NAME,UNIT_NAME,CUSTOMER_NAME) " +
"SELECT TAG_ID,MODEL_ID,CATEGORY_ID,DESCRIPTION,NOTES,STATUS_ID,PARK_ID,TOWER_ID,FLOOR_ID,UNIT_ID,CUSTOMER_ID,CHECK_OUT_DATE,DUE_DATE,MODIFIED_BY,MODIFIED_DATE,REVISION,PARK_NAME,TOWER_NAME,FLOOR_NAME,UNIT_NAME,CUSTOMER_NAME " +
"FROM PM_AM_ASSET_MASTER where id = ?";
preparedStatement = connection.prepareStatement(sql);
p.setString(1, id);
I am working on a school project where I must interact with an access database. I'm attempting to
SELECT Max(GameID) AS MaxID
FROM Games
However, This query when ran through the Eclipse application I built only returns in the console
SQL Exception: UCAExc:::4.0.3 Column not found: GameID
SQL State: S1000
Vendor Error: -421
I have checked the access database and the column DEFINITELY EXISTS. I ran the query in the access database and it worked in there as well. I'm not sure what I'm missing or if this is possible. How can i grab the highest value of gameID's?
here is the connection to the database
ResultSet rs = null; //will hold record that get returned
Statement stmt = null; //will hold the SQL statement we want to run
try
{
//2. Establish the connection
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://C:/Users/Public/ZaccaroBlottoDB.accdb");
//3. Create the statement
stmt = conn.createStatement();
String theQuery = "SELECT Max("
+ "GameID)"
+ " As MaxID"
+ " FROM Games"
+ " WHERE (1=1)";
//4. Execute the statement
rs = stmt.executeQuery(theQuery);
//5. Process the results
while (rs.next())
{
int gameID = rs.getInt("GameID"); //note the type and the field name from the DB
System.out.println(gameID);
//addGameIDFTF.setText(Integer.toString(gameID +1));
}//while
//6. Close the Connection
rs.close();
conn.close();
}
catch (SQLException ex)
{
System.out.println("SQL Exception: " + ex.getMessage());
System.out.println("SQL State: " + ex.getSQLState());
System.out.println("Vendor Error: " + ex.getErrorCode());
ex.printStackTrace();
} //catch
I think the issue is the value that you are retrieving. As you have mentioned the alias name to be MaxID you should get MaxID from result_set instead of GameID
Hence, It should be
int gameID = rs.getInt("MaxID");
instead of
int gameID = rs.getInt("GameID");
I have the following mysql statement to delete records from a DB that is working.
SET #email = 'delete#mailinator.com';
SET #userID = (SELECT id FROM USER WHERE email = #email);
DELETE FROM user_role_group WHERE user_id = #userID;
DELETE FROM user_client_setup WHERE user_id = #userID;
DELETE FROM USER WHERE id = #userID;
I want to run this same query in Java with a jdbc mysql connection. I have tried the following
public void deleteCoreUser(String email) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://db.com:3306/core","username","password");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("SET #email = '"+email+"';\n" +
"SET #userID = (SELECT id FROM user WHERE email = #email);\n" +
"DELETE FROM user_role_group WHERE user_id = #userID;\n" +
"DELETE FROM user_client_setup WHERE user_id = #userID;\n" +
"DELETE FROM user WHERE id = #userID;");
con.close();
System.out.println("Deleting user "+email+" from the Core DB");
}catch(Exception e){ System.out.println(e);}
}
I am getting this error when running
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 'SET #userID = (SELECT id
FROM user WHERE email = #email); DELETE FROM user_role_' at line 2
Use execute() instead of executeQuery() since it returns multiple ResultSet. See answer (Statement.execute(sql) vs executeUpdate(sql) and executeQuery(sql)) and add ?allowMultiQueries=true to the database url
"jdbc:mysql://db.com:3306/core?allowMultiQueries=true"
If the MySQL queries are running correctly in MySQL console, then there is no reason that same query will show syntax error when handling it with jdbc. You are making mistakes in implementing the queries with java and how java handles it.
public void deleteCoreUser(String email) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://db.com:3306/core","username","password");
Statement stmt = con.createStatement();
String sql = "SET #email = '" + email + "'";
stmt.execute(sql);
sql = "SET #userID = (SELECT id FROM USER WHERE email = #email)";
stmt.execute(sql);
sql = "DELETE FROM user_role_group WHERE user_id = #userID";
stmt.execute(sql);
sql = "DELETE FROM user_client_setup WHERE user_id = #userID";
stmt.execute(sql);
sql = "DELETE FROM USER WHERE id = #userID";
stmt.execute(sql);
con.close();
System.out.println("Deleting user " + email + " from the Core DB");
} catch(Exception e){ System.out.println(e);}
}
stmt.executeQuery is used when you try to get resultset from the queries. But in this case you are not asking for resultset. That's why no Resultset is necessary and only stmt.execute should work.
I suspect the issue is due to the allowMultiQueries flag in MariaDB. This defaults to false, meaning each query is essentially run in a vacuum and your SET #userID = (SELECT id FROM user WHERE email = #email); query doesn't know what #email is. To resolve this with you current code, set the database allowMultiQueries=true.
I am trying to insert user information taken from a registration form into Derby DB using a java servlet class.
I get connected to the DB on NetBeans right after the user clicks the submit button with the user's information filled out. Then it should run this method:
public void insertNewUser(String userName, String passWord, String lastName, String firstName, String age, char sex, String email) {
try {
stmt = conn.createStatement();
String insertNewUserSQL = "INSERT INTO " + studentsTable + " VALUES ('" + userName + "', '" + passWord + "', '" + lastName + "', '" + firstName + "', " + age + ", '" + sex + "', '" + email + "')";
System.out.println(insertNewUserSQL);
stmt.executeQuery(insertNewUserSQL);
stmt.close();
} catch(SQLException sqlExcept) {
sqlExcept.printStackTrace();
}
}
But I keep getting the following exception:
java.sql.SQLException: executeQuery method can not be used for update.
What does this mean exactly?
The SQL command is correct as I can do it manually on NetBeans SQL Command window.
Are there restrictions for servlets or something I don't know about?
Thanks in advance!
Since you are inserting a record, you should be using executeUpdate() not executeQuery().
Here are some methods that are usually misused:
boolean execute()
Executes the SQL statement in this PreparedStatement object, which may
be any kind of SQL statement.
ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and returns
the ResultSet object generated by the query.
int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which
must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement
that returns nothing, such as a DDL statement.
One more thing, your query is weak as it is vulnerable with SQL Injection. Please do parameterized by using PreparedStatement.
Sample Code Snippet:
String insertNewUserSQL = "INSERT INTO " + studentsTable + " VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(insertNewUserSQL);
pstmt.setString(1, userName);
// ... repeat this step until the last parameter ....
pstmt.setString(7, email);
pstmt.executeUpdate();
Java PreparedStatement
To update values you need to use an updatable ResultSet, as follows:
ResultSet res = preparedStatement.executeQuery(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
res.first();
res.updateInt("id", 2);
res.updateRow();
Alternatively, you can use the executeUpdate method of statement, as follows:
statement.executeUpdate("update table set id = 2");