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());
}
Related
I have to store questions in session afterward in List then insert them all into database by one click
my servlet
Question question = new Question(title, content, idExam);
request.getSession().setAttribute("question", question);
int quizKey = ExamDAO.add_question(question);
ArrayList<Question> ques = new ArrayList<Question>();
ques.add(question);
my dao
cnx = Connect.getConnection();
String req = "insert into question(title, content, id_examen) values(?,?,?)";
PreparedStatement st = cnx.prepareStatement(req, Statement.RETURN_GENERATED_KEYS);
st.setString(1, question.getTitre());
st.setString(2, question.getContenu());
st.setInt(3, question.getIdExamen());
st.executeBatch();
ResultSet rs = st.getGeneratedKeys();
if (rs.next()) {
quizKey = rs.getInt(1);
}
how to do that ?
Try st.executeUpdate(). This is usually used for manipulating statements like DELETE, INSERT or UPDATE. The method will return either the row count for SQL Data Manipulation Language (DML) statements or 0 for statements that return nothing.
If you have a List<Question> and you wish to insert all in one go then you have to utilize what is called as - batching or batch update. Refer here for more details
You will be iterating your list of questions and setting parameters for each question then adding that statement to batch (by using st.addBatch()) & then finally call - st.executeBatch().
In your code sample, you are executing a batch but there is only one prepared statement in that batch. You need as many prepared statements as number of questions in the list.
String req = "insert into question(title, content, id_examen) values(?,?,?)";
PreparedStatement st = cnx.prepareStatement(req, Statement.RETURN_GENERATED_KEYS);
for(Question question : ques){
st.setString(1, question.getTitre());
st.setString(2, question.getContenu());
st.setInt(3, question.getIdExamen());
st.addBatch();
}
st.executeBatch();
With this approach, you might have issues in collecting generated keys as illustrated in this SO question so if you really need those ids , you will have to turn off auto commit, execute updates in loop without batching, collected generated ids in a map or list for each insert statement and then finally commit your connection in the end.
I am having a problem with a ResultSet being closed. What confuses me is that it works for a portion of the data and then closes. At first I thought it might be because of connection timeout but that doesn't seem the case.
This portion of the program pertains to comparing an .xlsx workbook to an already present SQL database and for lack of a better term merges/updates it.
First, in my CompareDatabase class I am calling a search function that searches an SQLite database for a specific string every 6 iterations.
int columnCount = 6;
dataPoint = dataPoint.replaceAll("Detail", "");
String[] temp = dataPoint.trim().split("\\s+");
System.out.println(Arrays.toString(temp));
for (String tempDataPoint : temp) {
if ( columnCount == 6) {
System.out.println(search(tempDataPoint, connection));
}
columnCount = 0;
} else {
columnCount++;
}
}
This search function (also in the CompareDatabase class is then supposed to search for the value and return a String (was originally a Boolean but I wanted to see the output).
private String search (String searchValue, Connection connection) throws SQLException {
PreparedStatement pStatement = null;
pStatement = connection.prepareStatement("SELECT * FROM lotdatabase where (Vehicle) = (?)");
pStatement.setString(1, searchValue);
try (ResultSet resultSet = pStatement.executeQuery()){
return resultSet.getString(1);
}finally {
close(pStatement);
}
}
At the end you can see that the PreparedStatement is closed. The ResultSet should also be closed automatically (I read somewhere) but JDBC could possibly be being unreliable.
The Connection however is still open as it will be searching some 200+ strings and opening and closing that many times did not seem like a good idea.
These functions are called by my main class here:
One is commented out since it will error out because of primary key violation.
public static void main(String[] args) {
SQLDatabase sqlDatabase = new SQLDatabase();
//sqlDatabase.convertToSQL("Database1.xlsx");
sqlDatabase.compare("Database2.xlsx");
}
I have a suspicion that I am going about a bunch of this wrong (on the aspect of managing connections an such) and I would appreciate a reference to where I can learn to do it properly.
Also, being that PreparedStatement can only handle one ResultSet I don't see that being my issue since I close it every iteration in the for loop.
If more code or explanation is required please let me know and I will do my best to assist.
Thank you for taking the time to read this.
So after a bit more Googling and sleeping on it here is what worked for me.
The search function in compareDatabase changed to this:
private Boolean search (String searchValue, Connection connection) {
PreparedStatement ps = null;
try {
ps = connection.prepareStatement("SELECT * FROM lotdatabase where " +
"(Vehicle) = (?)");
ps.setString(1, searchValue);
ResultSet resultSet = ps.executeQuery();
//The following if statement checks if the ResultSet is empty.
if (!resultSet.next()){
resultSet.close();
ps.close();
return false;
}else{
resultSet.close();
ps.close();
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
And in the other function within compareDatabase I call the search function like this:
if (search(tempDataPoint, connection)) {
System.out.println("MATCH FOUND: " + tempDataPoint);
}else {
System.out.println("NOT FOUND: " + tempDataPoint);
}
This allows me to check the ResultSet and also be sure that it is closed.
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I’m beginner and I have problems with using MySql in Java with JDBC.
Can anybody paste a lines of code how to use “SQL UPDATE”.
Or maybe someone know about some good tutorials to learn it?
My code with mistakes:
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
Statement st = conn.createStatement();
String strUpdate = "UPDATE rozchody SET nazwa ='test' ";
ResultSet ra = st.executeQuery(strUpdate);
ResultSet rs = st.executeQuery("select * from rozchody");
while(rs.next()){
System.out.println("wyswietlam: ");
String s = rs.getString("nazwa");
System.out.println(s);
}
} catch (SQLException e) {
System.err.println(e);
} finally {
if (conn != null) {
conn.close();
}
}
For executing UPDATE/INSERT/CREATE statements you should use execute() function of Statement class and not executeQuery().
Corrected code :
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
Statement st = conn.createStatement();
String strUpdate = "UPDATE rozchody SET nazwa ='test' ";
st.execute(strUpdate); // or use executeUpdate()
It will return a boolean value that you can check and proceed.
follow this example here but this is essentially it
String strUpdate = "UPDATE rozchody SET nazwa ='test'";
PreparedStatement preparedStatement = conn.prepareStatement(strUpdate);
// execute insert SQL stetement
preparedStatement.executeUpdate();
When you want to do a UPDATE,INSERT,DELETE on a SQL database, you never receive a resultset.
Use executeUpdate instead of executeQuery.
Only one ResultSet object can be opened for a Statement. You're creating two ResultSet objects with your UPDATE and then your SELECT statements.
Since UPDATE does not return a ResultSet, use st.execute(strUpdate). Then you can retrieve a ResultSet with st.executeQuery("select * from rozchody");
Your fixed code:
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
Statement st = conn.createStatement();
String strUpdate = "UPDATE rozchody SET nazwa ='test' ";
//Change this
st.execute(strUpdate);
ResultSet rs = st.executeQuery("select * from rozchody");
//Now you won't get an error opening a new ResultSet
while(rs.next()){
System.out.println("wyswietlam: ");
String s = rs.getString("nazwa");
System.out.println(s);
}
} catch (SQLException e) {
System.err.println(e);
} finally {
if (conn != null) {
conn.close();
}
}
Note that while the above will work, it is generally better to use PreparedStatements rather than re-using a Statement for different executions. This will help prevent SQL injection, and you should read into it once you have a firmer grasp on how the Statement object works.
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 11 years ago.
How can I return a true/false value depending if a bit value is 1 or 0? The table has a list of usernames and a bit value of 1 or 0. I want to check if the bit value is 1 or 0.
How can I achieve this?
Just do
boolean value = resultSet.getInt("columnName") != 0;
It will be false when it's 0, otherwise true.
public class ValueDao {
public static final String SELECT_VALUE = "SELECT VALUE FROM MY_TABLE"; // WHERE clause?
private Connection connection;
public ValueDao(Connection connection) {
this.connection = connection;
}
public boolean hasValue(String value) throws SQLException {
boolean hasValue = false;
if (value != null) {
Statement st = null;
ResultSet rs = null;
try {
st = connection.createStatement();
rs = st.executeQuery();
while (rs.next()) {
String x = rs.getString(1);
if (value.equals(x)) {
hasValue = true;
break;
}
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DatabaseUtils.close(rs); // you write these cleanup methods.
DatabaseUtils.close(st);
}
return hasValue;
}
}
you can run query in java on connection like:
//Say you have a Connection conn
//Say column for bit value is USER_BIT
//and say 1st bit we are looking for
PreparedStatement stmt = conn.prepareStatement("select USER_BIT & 1 from USERS where USER_ID ='123'");
NOTE: Above code is for illustration. You might need to change it as per your need.