Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am wondering can i insert table name in this format
String update = "UPDATE ? SET Status = ? WHERE Name = ?";
stmt.setString(1,tableName);
stmt.setString(2,status);
stmt.setString(3,name);
same for insert and delete statements?
No.
The reason you place question marks in the query (aside from protection against SQL injection) is so that the database can prepare the statement once and use that prepared statement with different parameters. It wouldn't be able to prepare a statement if it doesn't know what table(s) you are using.
The short answer is no. But you can do it this way:
String update = "UPDATE " + tableName + " SET Status = ? WHERE Name = ?";
...
stmt.setString(1,status);
stmt.setString(2,name);
Be aware of the SQL injection though. Be sure your tableName comes from the secure source.
Normally, you would do this as shown below...
String sql = "UPDATE " + tableName " SET Status = ? WHERE Name = ?";
PreparedStatement stmt = null;
try {
stmt = connection.prepareStatement(sql);
stmt.setString(1, status);
stmt.setString(2, name);
stmt.executeUpdate();
} finally {
if (stmt != null) {
stmt.close();
}
}
No you cann't do this because you are definitely using a prepared statement. The reason you can not do this is PreparedStatement is pre-compiled so it needs the table which you are modifing (its data using DML) or structurally (using DDL). If you don't mention the table table name how the statement is going to be pre-compiled?
If you want you can use dynamic SQL but in that case you don't have to use PreparedStatement you can use it using a simpler implementation Statement.
Hope this is helpful !!
Related
This question already has an answer here:
SQLException: the result set is closed
(1 answer)
Closed 3 years ago.
I didn't find the reason for a SQLExeption, I got it at while(dbrs.next()). It is simple, it was working, but after update to Oracle Server 19, I got this error. I got still a result set in Oracle Developer with the same account.
Statement st = conn.createStatement();
if (Oracle){
ResultSet dbrs = st.executeQuery("select table_name from all_tables");
while(dbrs.next()){
if (dbrs.getString(1).equals(G_IN)){
st.execute("DROP TABLE "+G_IN);
System.out.println(G_IN+" gelöscht");
}
}
dbrs.close();
}else{
String loeschen="DROP TABLE IF EXISTS \"" + G_IN +"\"";
System.out.println(loeschen);
st.execute( loeschen );
}
You shouldn't reuse a Statement object as is the case in your while loop. To execute a new query, you need to use a new Statement object.
Replace
st.execute("DROP TABLE "+G_IN);
with
conn.createStatement().execute("DROP TABLE "+G_IN);
and it should work.
This question already has an answer here:
java.sql.sqlexception column not found
(1 answer)
Closed 4 years ago.
i need to get the last id entered in my data base witch is AUTO_INCREMENT so i did this
String Var = "SELECT MAX(id) FROM goupe ; ";
ResultSet vari=st.executeQuery(Var);
while(vari.next()){
nombre = vari.getInt("id");}
String sql = "INSERT INTO Student(name,famillyname,email,password,module,speciality,card,id_goupe)VALUES('"+name+"','"+familly+"','"+email+"','"+pass+"','"+module+"','"+specialite+"','"+card+"','"+nombre+"');";
st.execute(sql);
but i had this problem Column 'id' not found.
so what should i do to have it right .
I have to say, there are a couple of really easy things you can do to greatly improve your code.
If your latest ID is generated elsewhere, then embed the query directly into the statement such that you don't need to go get it. That will reduce the risk of a race condition.
Use PreparedStatements. Let me ask you this question: What do you suppose is going to happen if one of your user's name is O'Ryan?
Since your code is just a snip, I also will only provide a snip:
int index = 1;
String sql = "INSERT INTO Student(name,famillyname,email,password,module,speciality,card,id_goupe)" +
"VALUES(?,?,?,?,?,?,?,(SELECT MAX(id) FROM goupe));";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(index++, name);
ps.setString(index++, familyname);
ps.setString(index++, email);
ps.setString(index++, password);
ps.setString(index++, module);
ps.setString(index++, speciality);
ps.setString(index++, card);
int rows = ps.executeUpdate();
if(rows == 1) {
System.out.println("Successfully inserted row");
}
When you execute the query SELECT MAX(id) FROM goupe;, then in the returned table, the column name no longer remains as id.
So, the best approach is to provide a name for the column like below:
SELECT MAX(id) AS maxid FROM goupe;
Then, you can get the value using:
vari.getInt("maxid")
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I need to create a sql sequence in sql server programmatically from Java and I should be able to retrieve the continuous value from the sequence to program. First of all can I do so? If so how?
It's possible as all SQL servers provide some functionality and guarantee ACID rules. Even with very simple old MySql engine which didn't support transactions it's achievable. The easiest and widely supported approach is:
CREATE TABLE SequenceValue (
sequenceIdentifier varchar(124) NOT NULL PRIMARY KEY,
sequenceValue INT NOT NULL;
);
All you need to do in the program is:
Connection con = dataSource.getConnection();
try {
con.setAutoCommit(true);
PreparedStatement st = con.prepareStatement("SELECT sequenceValue SequenceValue WHERE sequenceIdentifier = ?");
st.setString(1, sequenceIdentifier);
SQLException retried = null;
for (;;) {
ResultSet rs = st.executeQuery();
if (!rs.next()) {
if (retried != null)
throw retried;
PreparedStatement ins = con.prepareStatement("INSERT INTO SequenceValue (sequenceIdentifier, sequenceValue) VALUES (?, ?)");
ins.setString(1, sequenceIdentifier);
ins.setLong(2, 0);
try {
ins.executeUpdate();
}
catch (SQLException ex) {
// store the exception and rethrow if next query retry fails
retried = ex;
}
}
else {
long value = rs.getLong(1);
PreparedStatement upd = con.prepareStatement("UPDATE SequenceValue SET sequenceValue = sequenceValue+1 WHERE sequenceIdentifier = ? AND sequenceValue = ?");
upd.setString(1, sequenceIdentifier);
upd.setLong(2, value+1);
if (upd.executeUpdate() == 1)
return value+1;
}
}
}
finally {
con.close();
}
Briefly: The code avoid transactions completely. At the beginning it tries to retrieve the sequence value according to identifier. In case it's not found, it attempts to create it and retries retrieving again. It doesn't fail in case the value was created in the meantime.
If the value is found, it tries to increment it using atomic update on the row. If it succeeds then it returns the incremented value, if not it retries again.
This question already has answers here:
Using Prepared Statements to set Table Name
(8 answers)
Closed 7 years ago.
Is there a limit to PreparedStatement variables (?) or requirements for their placement?
I have a method that takes in the parameters to complete a PreparedStatement however, it throws a SQLException.
Here is the PreparedStatement I want to use:
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
When I add in the first and second variables it runs just fine. Here is the working PreparedStatement:
String update = "UPDATE Student SET First_Name = ? WHERE UserID = ?";
Is there a reason I cannot get the first statement to work?
The entire method:
public static void runUpdate(String givenID, String givenAttribute, String givenUpdate) throws SQLException
{
// Establish the connection with the database
Connection conn = SimpleDataSource.getConnection();
try
{
// Create a string with the SQL Update statement
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
// Make a Prepared Statement with the connection to the database
PreparedStatement stat = conn.prepareStatement(update);
try
{
// Set the statement with the given parameters
stat.setString(1, Utility.getType(givenID));
stat.setString(2, givenAttribute);
stat.setString(2, givenUpdate);
stat.setString(3, givenID);
// Execute the Update Statement
stat.executeUpdate();
}
finally
{
// Close the prepared Statement
stat.close();
}
}
finally
{
// Close the connection to the database
conn.close();
}
}
You can't use the query like this.
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
You should write the name of table and the name of the column like here.
String update = "UPDATE table SET column_name = ? WHERE UserID = ?";
You can use variables in prepared statements only as placeholder of literals in SQL statements. So you cannot use them for column name, or table names. For these you should resort to dynamic SQL statements.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Hi i have code java swing to insert 2 lines in tables sql
and i insert in table 2 jtextfields that i set in frame
So i want don't insert line if i set the same text in jTextfields
this is the code:
Connection conn = null;
Statement stmt = null;
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+db, "root", "123456");
stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO router(hostname,address,version)VALUES('Edge 01','"+jTextField1.getText()+"','2700')" ) ;
stmt.executeUpdate("INSERT INTO router(hostname,address,version) VALUES('Edge 02','"+jTextField2.getText()+"','2700)" ) ;
stmt.close();
conn.close();
}
catch(SQLException ek){
}
Thank you
There are two possible options:
Try retrieving the record using select statement and insert only when if select results into ZERO records.
Create a unique key/index on the database table columns and let the inserts trigger. Insert will fail in case of duplicates but you need handle the exceptions (duplicate/unique).
If possible, apply both the steps together otherwise select one of the steps better suiting your other business scenarios.
I would suggest that you never, ever, build queries at Strings. Use a PreparedStatement.
Now, with that out of the way. You need to first query the database to see if it contains the desired value, if it doesn't insert it.
Move this logic into a separate method for clarity. And always close resources in a finally block, otherwise you get a memory leak if there is an Exception. I have used the Java 7 try-with-resources construct.
public boolean insertIfNotPresent(final Connection con, final String value) throws SQLException {
final String checkQuery = "SELECT COUNT(*) FROM router where hostname='Edge 01' and version=2700 and address=?";
try (final PreparedStatement statement = con.prepareStatement(checkQuery)) {
statement.setString(1, value);
try (final ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next() && resultSet.getInt(1) > 0) {
return false;
}
}
}
final String insertQuery = "INSERT INTO router SET hostname='Edge 01', version=2700, address=?";
try (final PreparedStatement statement = con.prepareStatement(insertQuery)) {
statement.setString(1, value);
statement.executeUpdate();
}
return true;
}
So the first query, SELECT COUNT(*) ..., counts rows matching the criteria. If there is already something in the database we return false.
The second query does the insert if we didn't return false from the first part. The method returns true in this case.
As an example in the above code, something like the following would work
try(final Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+db, "root", "123456")) {
insertIfNotPresent(conn, jTextField1.getText());
insertIfNotPresent(conn, jTextField2.getText());
}