How to overwrite old entry with newer one in mysql table? - java

I'm developing a webservice using JSON that inserts the email of g+ user(once the user chooses to login to my app through google sign-in).
I don't want my webservice to enter multiple entries for the same user into my table.
I want to overwrite the old entry of email with the newer one.
what should I do?
Edit 1:
//setGplusEmail
public ArrayList<Status> setEmail(Connection con,String gplusMail) throws SQLException
{
ArrayList<Status> gplusUserList = new ArrayList<Status>();
//con.setAutoCommit(false);
String sql = "INSERT INTO gpluslogin (gmail) VALUES ('"+gplusMail+"')";
String sql1 = "INSERT INTO gpluslogin (gmail) VALUES ('"+gplusMail+"') ON DUPLICATE KEY UPDATE (gmail = '"+gplusMail+"')";
PreparedStatement stmt = con.prepareStatement(sql);
PreparedStatement stmt1 = con.prepareStatement(sql1);
try{
stmt.executeUpdate();
stmt1.executeUpdate();
}catch(Exception e){
}
Status s = new Status();
s.setStatus("Successfully Inserted...");
gplusUserList.add(s);
return gplusUserList;
}
Is this the right way to execute?

After creating unique key on gmail column you can use any one statement out of below 2-
REPLACE INTO gpluslogin (gmail) VALUES('abc#gmail.com');
OR
INSERT INTO gpluslogin (gmail) VALUES('abc#gmail.com') ON DUPLICATE KEY UPDATE gmail='abc#gmail.com';

UPDATE user_table SET email=$newemail WHERE userID = $userID

Related

how to update a data to the database using JDBC

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

Insert data and if already inserted then update in sql

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();
}
}
}

Best way to check if the record is exist

what is the best way to check if the user is exist
i have wrote this code
try{
PreparedStatment mPre=conn.preparedStatement(INSERT INTO TABLE VALUES(?,?);
}catch(Exception e)
{
if(e.getMessage().contains("Dublicated"))
{
throw new Exception("user is exist");
}
}finally {
mPre.close();
conn.close();
}
my friends told me that this is stupid query
and i should do like this
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("SELECT COUNT(*) AS total FROM .......");
int cnt = rs.getInt("total");
Your friend is right. You can check if row exists by query:
SELECT EXISTS(SELECT 1 FROM *table* WHERE *something*)
As long as you are trying to insert a row that breaks the unique primary key constraint of database tables AND the exception thrown has a stack trace that contains the word "duplicated" then your code should work fine.
But in the unlikely event that the stack trace changes and does NOT contain that word, your code won't work anymore.
It's more likely that you are trying to insert a row with a unique primary key value but an existing username, which won't give you the error that you hope for. That's the reason why it would be smarter/safer to retrieve results for that username and count how many results there are.
When you are trying to verify if the given username and password exists in your user table, you should use PreparedStatment because it will help you in protecting your application from SQL injection.
But
Inserting a new user to the database is not the right way to do user validation.
You can do something like this example:
String selectSQL = "SELECT * FROM USER_TABLE WHERE USER_ID = ? AND PASSWORD = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setInt(1, 1001);
preparedStatement.setString(2, "1234");
ResultSet rs = preparedStatement.executeQuery(selectSQL );
while (rs.next()) {
//You will need user information to render dashborad of your web application
String userid = rs.getString("USER_ID");
String username = rs.getString("USERNAME");
}
Complete code refrence: http://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/

How to get the Generated insert ID in JDBC?

My source code has the following structure:
SourceFolder
AddProduct.jsp
Source Packages
-Controller(Servlets)
SaveProduct.java
-Model(Db Operations)
ProductDbOperations.java
I am inserting a new product into the product table and at the same time I am inserting an entry into product_collection table (product_id | collection_id).
To insert an entry into the product_collection table i need to get generated id from product table. After that a new entry is inserted into the product_collection table.
Also, I am not using any Framework and am using Netbeans 7.3.
Problem:
A new entry is inserted into the product table with this piece of code
IN: ProductDbOperations.java
try
{
this.initConnection(); // Db connection
pst = cn.prepareStatement("INSERT INTO product values('"+name+"', "+quantity+", "+price+")");
rs = pst.executeUpdate();
}
catch(SQLException ex)
{
}
I Also used the solution at following link which doesn't works for me.
I didn't got any SQL exception
How to get the insert ID in JDBC?
so help me find out why this code not working for me .
Thanks a million.
Not all drivers support the version of getGeneratedKeys() as shown in the linked answer. But when preparing the statement, you can also pass the list of columns that should be returned instead of the "flag" Statement.RETURN_GENERATED_KEYS (and passing the column names works more reliably in my experience)
Additionally: as javaBeginner pointed out correctly, your usage of a prepared statement is wrong. The way you do it, will still leave you wide open to SQL injection.
// run the INSERT
String sql = "INSERT INTO product values(?,?,?)";
pst = cn.prepareStatement(sql, new String[] {"PRODUCT_ID"} );
pst.setString(1, name);
pst.setInt(2, quantity);
pst.setInt(3, price);
pst.executeUpdate();
// now get the ID:
ResultSet rs = pst.getGeneratedKeys();
if (rs.next()) {
long productId = rs.getLong(1);
}
Note that the column name passed to the call is case-sensitive. For Oracle the column names are usually uppercase. If you are using e.g. Postgres you would most probably need to pass new String[] {"product_id"}
The way you are using is not the proper way of using preparedstatement
use the following way
pst = cn.prepareStatement("INSERT INTO product values(?,?,?)");
pst.setString(1,name);
pst.setInt(2,quantity);
pst.setInt(3,price);
pst.executeUpdate();
Yes there is a way to retrieve the key inserted by SQL. You can do it by:
Using Statement.RETURN_GENERATED_KEYS in your previous insert and get the key which can be used in further insert
e.g:
String query = "INSERT INTO Table (Col2, Col3) VALUES ('S', 50)";
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);

Iterate through resultset [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting unexpected output in program
To be frank,this question may be silly to ask, but I'm a novice in Java.
This is my Table emp(name,id,address,date).
Now I'm going to match a certain employee's corresponding password.
String sql = "select emp_id,password from regid";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
// here will be iterate function using resultset,i guess
// what should be the best logic to check the name and password...any inputs
//in terms of code
if(if (employee.equals(rs.getString("emp_id")) && password.equals(rs.getString("password")))){
You are Mr. emp // in terms of code
}
else{
Who are You ?? //in terms of code
}
}
Any inputs will be highly appreciated.
Use a PreparedStatement to create your query. So your parameterized query for the PreparedStatement would be something like this:
SELECT * from regid WHERE emp_id = ? AND password = ?
Plug in the paremeter values and execute your statement. So it would be something like this:
PreparedStatement ps = null;
ResultSet rs = null;
boolean validUser = false;
try{
ps = connection.prepareStatement("SELECT * from regid WHERE emp_id = ? AND password = ?");
ps.setString(1, [user_id_input]);
ps.setString(2, [user_pw_input]);
rs = ps.executeQuery();
validUser = rs.next();
}finally{
//Release your resources
}
if(validUser){
//user is validated
}
As a side note, I would also suggest to validate your user's input before feeding it to your query.
You are selecting the data for all employees and looking through them for a match.
Much better to have the database filter it:
select count(*) from regid where emp_id = ? and password = ?
Then you only need to check if this returns 0 or 1.
Also, password is hopefully just a password hash.
fetching all data from database make your application performance slow, So fire following query retrieve one record.
boolean status = false;
String emp_name = "";
String emp_password = "";
String sql = "select * from regid where emp_id='"+emp_id+"' AND password='"+password+"'";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
if(emp_id.equals(rs.getString("emp_id")) && password.equals(rs.getString("password")))
{
// fetch employee data
status = true;
}
}
if(status)
{
// login correct
}
else
{
// login incorrect
}
Query your database with "select emp_id,password,... from regid where emp_id=? and password=?"
Create a PreparedStatement and set emp_id and password. it will return you 1 row if emp_id and password match.
You actually shouldn't be matching the password in the result set. Your sql query should be something like
select emp_id from regid where password='userpassword'
where userpassword is the password you got from the screen your using

Categories