I simply want to insert the data to a SQL database table and if there is some data inserted already then I want to update that data. How can I do this using Java. Kindly help me, and sorry for bad English in advance.
The standard SQL statement for INSERT (if new) or UPDATE (if exists) is called MERGE.
Since you didn't specify which DBMS dialect you're asking about, I'll refer you to the Wikipedia article "Merge (SQL)", which covers most DBMS dialects. Summary:
MERGE INTO tablename USING table_reference ON (condition)
WHEN MATCHED THEN
UPDATE SET column1 = value1 [, column2 = value2 ...]
WHEN NOT MATCHED THEN
INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...])
Database management systems Oracle Database, DB2, Teradata, EXASOL, CUBRID, MS SQL and Vectorwise support the standard syntax. Some also add non-standard SQL extensions.
MySQL: INSERT ... ON DUPLICATE KEY UPDATE
SQLite: INSERT OR REPLACE INTO
PostgreSQL: INSERT INTO ... ON CONFLICT
You could use the EXISTS keyword to check for the existance of rows:
IF EXISTS (SELECT TOP 1 * FROM...)
BEGIN
UPDATE....
END
ELSE
BEGIN
INSERT...
END
Just identify the unique item in your data set (like Id or a code). Then by using that try to do a SELECT query first. If the Resultset is empty, do the INSERT else try to UPDATE the details.
you have to first check the data exist in table
if exist then use update query otherwise insert data
its simple
try to following way:
Example Query
INSERT INTO table (id, name, city) VALUES(1, "ABC", "XYZ") ON DUPLICATE KEY UPDATE
name="ABC", city="XYZ"
for more help see documentation.
Click here
Set any field as the unique identity.
For an example consider that employee details has to be entered in the table name **EmployeeDetails.**in this case employee_id can be considered as unique.
use SELECT query
select * from EmployeeDetails where employee_id= "the unique keyvalue";
if the resultset is not empty then use UPDATE query to update the fields.
update EmployeeDetails set Employee_id=?,Full_name=?, Designation=?, Email_id=?, Password=? where Employee_id='"
+ id + "'";
If the resultset is empty then use the INSERT query to insert the values to the table
Insert into EmployeeDetails values(...)
package com.stackwork;
//STEP 1. Import required packages
import java.sql.*;
import java.util.Scanner;
public class Updation {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Employee";
// Database credentials
static final String USER = "root";
static final String PASS = "admin";
private static Scanner sc;
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
//STEP 5: Get the employee_id for whom data need to be updated/inserted
sc = new Scanner(System.in);
System.out.println("Enter the Employee_id for the record to be updated or inserted");
int Emp_idvalue=sc.nextInt();
sql = "SELECT * FROM EmployeeDetails where Emp_id="+Emp_idvalue;
ResultSet rs = stmt.executeQuery(sql);
if (!rs.next())
{
//STEP 6: If the previous details is not there ,then the details will be inserted newly
System.out.println("Enter the name to be inserted");
String Emp_namevalue =sc.next();
System.out.println("Enter the address to be inserted");
String Emp_addvalue =sc.next();
System.out.println("Enter the role to be inserted");
String Emp_rolevalue =sc.next();
PreparedStatement ps = conn
.prepareStatement("insert into EmployeeDetails values(?,?,?,?)");
ps.setString(2, Emp_namevalue);
ps.setString(3, Emp_addvalue);
ps.setString(4, Emp_rolevalue);
ps.setInt(1, Emp_idvalue);
ps.executeUpdate();
System.out.println("Inserted successfully");
}
else
{
//STEP 7: If the previous details is there ,then the details will be updated
System.out.println("Enter the name to be updated");
String Emp_namevalue =sc.next();
System.out.println("Enter the address to be updated");
String Emp_addvalue =sc.next();
System.out.println("Enter the role to be updated");
String Emp_rolevalue =sc.next();
String updateQuery = "update EmployeeDetails set Emp_id=?,Emp_name=?, Emp_address=?, Emp_role=? where Emp_id='"
+ Emp_idvalue + "'";
PreparedStatement ps1 = conn.prepareStatement(updateQuery);
ps1.setString(2, Emp_namevalue);
ps1.setString(3, Emp_addvalue);
ps1.setString(4, Emp_rolevalue);
ps1.setInt(1, Emp_idvalue);
ps1.executeUpdate();
System.out.println("updated successfully");
}
//Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
}
Related
Here is the code for my servlet which recieves username parameter from a registration form
String tusername=request.getParamater("un");
String dbURL="db.com";
String dbusername= "lc";
String dbpassword="lcpw";
Connection con=(Connection) DriverManager.getConnection(dbURL,dbusername,dbpassword);
Statement stmt= con.createStatement();
String query="SELECT * FROM users.username WHERE username=(tusername)";
ResultSet rs= stmt.executeQuery(query);
if(rs.next()==false){
//create new userobject with value of tusername
}
My question is how do I create a new user object with calue of tusername, would it be like so ?
if(rs.next()==false){
Statement stmt=con.createStatament();
String query="INSERT INTO user.username VALUE 'tusername'";
ResultSet rs= stmt.updateQuery(query);
}
I understand some of this might be archaic (such as not using a prepared statement) , I am just trying to better my understanding and I think I am having some small syntax issues, thanks :)
You should be using a NOT EXISTS query to do the insert, and also you should ideally be using a prepared statement:
String sql = "INSERT INTO user.username (username) ";
sql += "SELECT ? FROM dual WHERE NOT EXISTS (SELECT 1 FROM user.username WHERE username = ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, tusername);
ps.setString(2, tusername);
int result = ps.executeUpdate();
if (result > 0) {
System.out.println("Inserted new user " + tusername + " into username table";
}
else {
System.out.println("User " + tusername + " already exists; no new record was inserted");
}
I don't know what your actual database is. The above should work out of the box for MySQL and Oracle. It might need to be modified slightly for other databases.
An alternative to the above query would be to just use your current insert, but make the username column a (unique) primary key. In that case, any attempt to insert a duplicate would fail at the database level, probably resulting in an exception in your Java code. This would also be a more database agnostic approach.
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe",
"system", "9900479852");
Statement stmt =con.createStatement();
ResultSet rs = stmt.executeQuery("select *from registration where emailid='"+str+"' ");
// here im fetching the emailid from data base
while(rs.next()){
emailId = rs.getString("emailId");
mob = rs.getString("mobilenumber");
System.out.println(emailId);
//here we return update query`enter code here`
if(emailId.equals(str)){
stmt.executeQuery("update registration set password='"+s1+"'
where emailId='"+str+" '"); //query is executing but new vales are not updating to the data base
p.println("updated");
}
con.close();
}
trying to update the data to the database i'm not able update ,sql query is executing but data is not updating to data base.
Based on your code snippet, your code is trying to update database but indirectly fall into unnecessary process. Here is my correction, let say we have table (registration) in database consist of structure --> emailId (varchar 10), password (varchar 8).
Suppose you need to update 'registration', for each row when contain emailID = "gmail001" you'll set password to "myPassword". SQL statement for updating is UPDATE registration SET password = "myPassword" WHERE emailId="gmail001"
Back to your code, instead use 'Statement' class, you're prefer to use 'PreparedStatement' class for preconfigured SQL statement. Here is my corrections :
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "system", "9900479852");
String sql = "UPDATE registration SET password=? WHERE emailID=?";
String newPassword = "myPassword";
String keyEmailId = "gmail001";
try{
PreparedStatement stat = con.prepareStatement(sql);
stat.setString(1, newPassword);
stat.setString(2, keyEmailId);
stat.executeUpdate();
}catch(SQLException ex){
ex.printStackTrace();
}
}
For more information please visit oracle javaSE tutorial for JDBC implementations --> https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
I have a H2 database named PRODUCTS, with 5000 rows and 55 columns per row. I'm currently using a PreparedStatement to add rows of values to the database, but it does not check whether the row exists already. Instead, I need to only insert the row if the column name "id" (type VARCHAR) does not contain a certain alpha-numeric string, and if the column name "id2" (type VARCHAR) does not a certain alpha-numeric string, and if the column name "raw_yn" (type BOOLEAN) contains false. The values I enter into the prepared statement are provided via a method.
The question here is very close to what I'm asking, with the difference being the fact that it's solution is based on adding rows to an empty DB, and ensures the database is empty. The creator of H2 commented saying:
Then the "where not exists" ensures this rows are only inserted if the
table [TABLE] is empty.
How do I adapt this code so that it only performs the INSERT query if my above 3 requirements are met (whether or not DB is empty)?
Currently I have:
import java.sql. *;
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:~/myDB";
static final String USER = "test";
static final String PASS = "test";
static final Connection conn = null;
static final Statement stmt = null;
public class DataBaseManager {
public void insertIntoDB(String id1val, String id2val, Boolean raw_yn_val, ...,...) {
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
myStatement = "INSERT INTO PRODUCTS VALUES(?,?,?,..,...)";
stmt = conn.prepareStatement(myStatement);
stmt.setString(1, id1val);
stmt.setString(2, id2val);
stmt.setBoolean(3, raw_yn_val);
stmt.setString(4,....);
// Continue up to 55
stmt.executeUpdate();
}
[catch&finally blocks]
}
}
What should myStatement be changed to? I'm confused because if I use select 0, 'id1' union like below, how does that fit into my PreparedStatement of stmt.setString(1, id1val); ??. Thanks for your help.
INSERT INTO PRODUCTS SELECT * FROM(
select 0, 'id1' union // <--- How does this fit into Prepared Statement?
select 1, 'id2' union
select 2, 'raw_yn' union
) x where not exists(SELECT * FROM PRODUCTS); // <--- Ensures only works when empty
UPDATE:
Following Gord's suggestion, I've put together the following code. If the database is empty, n will return 0. This takes about 1 minute to add 5000 rows to the empty database. However, if there IS a match, it's taking nearly 5x longer, even though I'm merely using return as opposed to using additional INSERT code. So shouldn't it be faster?
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
statement = conn.createStatement();
String sql = "SELECT COUNT(*) AS n FROM PROPERTIES WHERE id1='" + id1 + "' AND id2='" + id2 + "' AND raw_yn='true'";
rs = statement.executeQuery(sql);
rs.next();
if (rs.getInt("n") == 0) {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
myStatement = "INSERT INTO PROPERTIES VALUES(?,?,?,...)";
stmt = conn.prepareStatement(myStatement);
stmt.setString(1, id1);
stmt.setString(2, id2);
stmt.setBoolean(3, raw_yn);
stmt.executeUpdate();
} else {
return; // <-- Takes 5x longer to go through ???
}
}
[catch & finally blocks]
Consider using a staging temp table where you append all data as is into a similar structured table, ProductsTemp, and then migrate to final table, Products, filtered for the unique rows. Below are the SQL statements to incorporate in your Java code in this order:
Staging Append (two statements)
DELETE FROM ProductsTemp;
INSERT INTO ProductsTemp VALUES (?,?,?,..,...);
Final Migration
INSERT INTO Products (id, id2, raw_yn, ...)
SELECT id, id2, raw_yn, ...
FROM ProductsTemp temp
WHERE NOT EXISTS (SELECT 1 FROM Products sub
WHERE sub.id = temp.id
AND sub.id2 = temp.id2
AND sub.raw_yn = temp.raw_yn);
I am trying to add two strings on two separate columns columns of my database using Java but I'm not sure what I am doing wrong. The code I am using
try{
Connection conn = DriverManager.getConnection(
"jdbc:ucanaccess://C:/Users/nevik/Desktop/databaseJava/Employee.accdb");
Statement st = conn.createStatement();
String sql = "Select * from Table2";
ResultSet rs = st.executeQuery(sql);
rs.updateString("user", user);
rs.updateString("pass", pass);
rs.updateRow();
}
catch(SQLException ex){
System.err.println("Error: "+ ex);
}
The first column on my database is user and the next one is pass. I am using UCanAccess in order to access my database.
This is how you normally update a row in java:
String query = "update Table2 set user = ?, pass= ?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt (1, user);
preparedStmt.setString(2, pass);
// execute the java preparedstatement
preparedStmt.executeUpdate();
First of, you've not updated the position of the current cursor in the ResultSet, which means that it's pointing to nothing...
You could use...
if (rs.next()) {
rs.updateString("user", user);
rs.updateString("pass", pass);
rs.updateRow();
}
But this assumes two things...
You have a database that supports updating values in the ResultSet and
You want to update the existing values.
To insert a value into the database, you should be using the INSERT command, for example...
try(Connection conn = DriverManager.getConnection(
"jdbc:ucanaccess://C:/Users/nevik/Desktop/databaseJava/Employee.accdb")) {
try (PreparedStatement stmt = conn.prepareStatement("INSERT into Table2 (user, pass) VALUES (?, ?)") {
stmt.setString(1, user);
stmt.setString(2, pass);
int rowsUpdated = stmt.executeUpdate();
}
}
catch(SQLException ex){
System.err.println("Error: "+ ex);
}
You might like to take some time to go over a basic SQL tutorial and the JDBC(TM) Database Access trail
As a side note...
You should not be storing passwords in Strings, you should keep them in char arrays and
You should not be storing passwords in the database without encrypting them in some way
#guevarak12
About the original question (how to use updatable ResultSet):
your code is wrong, you have to move the cursor in the right position.
In particular, if you are inserting a new row you have to call rs.moveToInsertRow(); before rs.updateString("user", user).
If you are updating an existent row, you have to move the cursor calling rs.next() and so reach the row to update.
Also you have to create the Statement in a different way:
Statement st =conn.createStatement( ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
See junit examples in the UCanAccess source distribution, class net.ucanaccess.test.CrudTest.
All other comments seem to be correct.
Firstly, I'm reading the product name and number of products from user using jTextFields. For that product I read the product id and price from database using sql query. But in the below code I display the product price in a jtextField but while running tha file I get query executed successfully but I'm not getting anything in the jtextField.
And please check the sql query and resultset use,
table name is "item" and database name is "myshop",
I declared variables globelly and this code is in a jButton's 'ActionPeformed" part.
String item_name=name.getText();
int item_no=Integer.parseInt(no.getText());
String sql="SELECT id,price FROM item WHERE item.name='item_name'";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/myshop","root","mysql");
java.sql.Statement stmt=con.createStatement();
if (stmt.execute(sql)) {
rs = stmt.getResultSet();
JOptionPane.showMessageDialog(this, "succes","executed query",JOptionPane.PLAIN_MESSAGE);
} else {
System.err.println("select failed");}
int idIndex = rs.findColumn("id");
int priceIndex = rs.findColumn("price");
while(rs.next()){
item_id=rs.getInt(idIndex);
item_price=rs.getInt(priceIndex);
jTextField1.setText(""+item_price);//displaying product price in a jTextField1
jTextField2.setText(""+item_id);//displaying product id in a jTextField2
}
}
catch(Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
}
This line should be
String sql="SELECT id,price FROM item WHERE item.name='item_name'";
like this
String sql="SELECT id,price FROM item WHERE item.name='"+item_name+"'";
Use a PreparedStatement so you don't have to worry about delimiting all the variables:
String sql="SELECT id, price FROM item WHERE item.name = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, item_name);
ResultSet rs = stmt.executeQuery();
Then the prepared statement will replace the variable for you with the proper quotes.
you would need to take item_name as param and put in quotes,
String sql="SELECT id,price FROM item WHERE item.name='"+ item_name+"'";
Try to avoid this type of mistake by using PreparedStatement
String sql="SELECT id,price FROM item WHERE item.name=?";
PreapredStatement ps = con.prepareStatement(sql);
ps.setString(1,item_name);
ResultSet rs = ps.executeQuery();
Use of PreparedStatement also prevent SQL injection attack.
try this code .
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myshop","root","mysql");
PreparedStatement pt=con.prepareStatement("SELECT id,price FROM item WHERE item.name=?");
pt.setString(1,"item_name");
ResultSet rs;
if(pt.execute())
{
rs=pt.getResultSet();
JOptionPane.showMessageDialog(this, "succes","executed query",JOptionPane.PLAIN_MESSAGE);
}
else {
System.err.println("select failed");
}
while(rs.next()){
item_id=rs.getInt(1);
item_price=rs.getInt(2);
jTextField1.setText(""+item_price);//displaying product price in a jTextField1
jTextField2.setText(""+item_id);//displaying product id in a jTextField2
}
First, you need an reader, like this
private static void reader() throws SQLException {
DataBaseName db = new DataBaseName ();
names = db.getNames();
}