how to update a data to the database using JDBC - java

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

Related

Why does this Query return NULL?

I have a derby users database which I query, when the user clicks login on the application.
However, when I query the users table with the parameter [user] derby returns a null Object instead of the record it ought to return.
Here is my code:
String ssql = "SELECT * FROM USERS WHERE UNAME LIKE ?";
try{
DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
con = DriverManager.getConnection(url);
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
try{
while (rs.next()) {
if(rs.getString("PW").toCharArray().equals(txt_password.getPassword())){
sql.close();
con.close();
return true;
}
} catch (NPE ...) {...}
}
I tried it multiple times wit a test user with both the pw and the username set to "test"; but I always get the same error.
Why is the recordset always Null?
Thanks for your help :)
The documentation says
ResultSet getGeneratedKeys() throws SQLException
Retrieves any auto-generated keys created as a result of executing this Statement
object.
If this Statement object did not generate any keys, an empty
ResultSet object is returned.
Your select statement isn't generating any keys that's why it's returning an empty ResultSet. You aren't inserting anything hence no keys are being generated.
You can try ResultSet rs = sql.executeQuery();. It should work.
You are using it in wrong way.
The generated keys concept should be used only in the case DML of insert type query but not in the case of select query.
select simply select the rows from the table. In this case there is no chance of any keys getting generated.
In the case of insert query if any column is configured as auto increment or kind of functionality then some keys will get generated. These keys can be caught using Statement.RETURN_GENERATED_KEYS in java.
As you are using select query there is no need of using Statement.RETURN_GENERATED_KEYS.
You just modify below lines and everything will be fine.
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
with
sql = con.prepareStatement( ssql );
sql.setString( 1, cbox_chooseUser.getSelectedItem().toString() );
ResultSet rs = sql.executeQuery();

Logs for SQL queries in Java using Eclipse

If I am using the below code query the database, where would I find the log file for the process? I am looking for what is being sent to the database. The query works from SQL Server Management Studio. The database is MS-SQL 2008.
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String userName = "dbuser";
String password = "dbpswd";
String url = "jdbc:jtds:sqlserver://server:1043"+";databaseName=databasename";
Connection con = DriverManager.getConnection(url,userName,password);
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery
("SELECT users.id,users.role FROM users WHERE users.username = 'xusername' AND users.password = 'xpswd' AND users.active = 1");
}
When the code runs it returns
'No current row in the ResultSet.'
If I use
System.out.println(stm);
it returns
net.sourceforge.jtds.jdbc.JtdsStatement#7fd2c698
You have to use
rs.next()
to retrieve the first entry. A ResultSet cursor is initially positioned before the first row.

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

How to insert two strings into my Access database from Java using UCanAccess?

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.

How to perform a search in an SQL database with a java application?

I'm planning to build a very very simple java application done on Netbeans that accepts basic individual information like ID number, name, and address and stores it on an sql database.
I want to put a search function on my program that accepts ID numbers. When the user inputs the ID number that is stored in the database, it will show the Name and address on a pop up message dialog.
I know this is possible but can you link me to some guides or documentations about the search function? or maybe you could give me a very short example of a sample code done in the search button?
Have a look at this link
It is using classes such as Connection and PreparedStatement
Pseudo-code being
String selectSQL = "SELECT USER_ID, USERNAME FROM DBUSER WHERE USER_ID = ?";
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setInt(1, 1001);
// execute select SQL stetement
ResultSet rs = preparedStatement.executeQuery();
try {
while (rs.next()) {
String userid = rs.getString("USER_ID");
String username = rs.getString("USERNAME");
System.out.println("userid : " + userid);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
preparedStatement.close();
dbConnection.close();
}
http://docs.oracle.com/javase/tutorial/jdbc/basics/
Look into how to use JDBC.
A very basic example:
Connection c = null; //need to initialize a java.sql.Connection from JDBC.
String sql = "SELECT * FROM Users WHERE name = ?";
PreparedStatement ps = c.prepareStatement(sql);
ps.setString(1, "John Smith");
ResultSet rs = ps.executeQuery();
List<String> matchingNames = new ArrayList<>();
while (rs.next())
{
String name = rs.getString("name");
matchingNames.add(name);
}
for (String name: matchingNames)
{
//Display dialog.
}
This link is a very good JDBC tutorial. JDBC is the way that java uses database, but this is so basic that almost no real project use JDBC directly.
If you want to learn more, try MyBatis and Hibernate which are the most popular ORM framework, and both of them are based on JDBC.
PS. http://www.mkyong.com/ this site has many good tutorials for Java developer

Categories