How to create and execute an SQL update statement - java

I have a table inside consist of variable like Username, ContactNo, Date, Name.
And i would like to do a update for Username and ContactNo only to the original record in the database.
How can i make use of update sql statement to do it?
Below is my SELECT sql statement.
public void dbData(String UName)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/assignment","root","mysql");
ps = con.createStatement();
SQL_Str="Select username,numberOfBid from customer where username like ('" + UName +"')";
//SQL_Str="Select * from customer";
rs=ps.executeQuery(SQL_Str);
rs.next();
dbusername=rs.getString("username").toString();
dbbid=rs.getInt("numberOfBid");
//UName2 = rs.getString("username").toString();
UName2 = username;
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Exception Occur :" + ex);
}
}

http://dev.mysql.com/doc/refman/5.0/en/update.html
And please study...

Here is a quick and dirty solution: when you have modified your values, just add something like this
String updSQL = "udate table set numberOfBid = " + dbbid + " where user = " + UName;
ps.executeUpdate(updSQL);
There are however 1000 improvements you can make such using prepared statementsand placeholders:
String updSQL = "udate table set numberOfBid = ? where username like ?";
PreparedStatement pstmt = con.prepareStatement(updSQL);
pstmt.setInt(0, dbbid);
pstmt.setString(1, UName);
pstmt.execute();
May I suggest you to have a look at Hibernate, Spring JDBC, JPA... which are on a much higher level than JDBC is.

Related

How can I only get 1 element from a SQL Database?

I have a small problem. I wrote a method in which I have an SQL query that should output a correct string after 2 parameters. When debugging, however, the result is not the right element. I don't know why this happens.
public static String findRightTemplate(String user_name, int template_id)
throws Exception {
Connection conn = DriverManager.getConnection(
"xxx", "xxx", "xxx");
Statement st = conn.createStatement();
st = conn.createStatement();
ResultSet rs = st.executeQuery(
"SELECT template FROM templates " +
"where template_id=template_id AND user_name=user_name"
);
String temp="";
while(rs.next())
{
temp=rs.getString("template");
}
rs.close();
st.close();
conn.close();
I ask for the username and template_id and I just want to get an element out of the template column.
The SQL query is correct. I've already tested that. But it seems that the query runs through all elements with the same username. As a result, I only get the last element and not the right one.
UPDATE
Currently you do not use the method parameters inside your query. As already suggested you should use a PreparedStatement to fix that. You should basically do the following:
public static String findRightTemplate(String userName, int templateId) throws SQLException {
try (final Connection connection = DriverManager.getConnection("...")) {
final PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT template " +
"FROM templates " +
"WHERE user_name = ? " +
"AND template_id = ? " +
"LIMIT 1"
);
preparedStatement.setString(1, userName);
preparedStatement.setInt(2, templateId);
final ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getString(1);
}
}
return null;
}
If you do not use a PreparedStatement and build the query manually as suggested in the comments your application could be vulnerable to SQL injection attacks.

inserting new user object into JDBC through the servlet

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.

SQL exception, Generated keys not requested

This exception is occur in mentioned section of my code:
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "Insert into ...";
try {
con = DriverManager.getConnection(...);
ps = con.prepareStatement(query, java.sql.Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate(query);
rs = ps.getGeneratedKeys(); // Exception is here
}
while (resultset.next()) {
id = String.valueOf(resultset.getInt(1));
}
Exception:
Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement()
My purpose is inserting a new record and save the first field (id) (that is auto_increment) to variable id.
You are using the wrong execute method. Instead of the one taking a String, you should use one without a parameter. And as Chris Joslin mentioned, for INSERT it is better to use executeUpdate.
Technically a correct JDBC driver should throw an SQLException immediately when calling execute(String) or one of its siblings on a PreparedStatement, but some drivers ignore this rule.
Try ps.executeUpdate() instead of ps.execute().
Shouldn't it be:
String query = "Insert into Books(Name,ISBN,Status,Date)" +
"values( '" + name + "','" + isbn + "','" + status+ "','" + date + "' ) ";
try {
con = DriverManager.getConnection(...);
ps = con.prepareStatement(query,java.sql.Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
rs = ps.getGeneratedKeys(); // Exception is here
}
It looks like in your first example, you do a prepare correctly, but then call the executeUpdate with the Query String again instead of just the ps.executeUpdate().
ps = con.prepareStatement(query, java.sql.Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate(query);

SQL command from eclipse using JDBC

I have been searching and trying different stuff for awhile, but have not found an answer. I'm trying to make a connection to sql using JDBC from eclipse. I am having trouble when I need to select a string in the database. If I use:
Select name from data where title = 'mr';
That works with terminal/command line but when I try to use eclipse where I use
statement sp = connection.createstatement();
resultset rs = sp.executequery("select name from data where title = '" + "mr" + "'");
It does not give me anything while the terminal input does. What did I do wrong in the eclipse? Thanks
Heres a part of the code. Sorry, its a bit messy, been trying different things.
private boolean loginChecker(String cid, String password) throws SQLException{
boolean check = false;
PreparedStatement pstatment = null;
Statement stmt = null;
//String query = "SELECT 'cat' FROM customer";
String query = "select '"+cid+"' from customer where password = '"+password+"'";
try {
System.out.println("in try......");
//stmt = con.createStatement();
//ResultSet rs = stmt.executeQuery(query);
PreparedStatement prepStmt = con.prepareStatement(query);
ResultSet rs = prepStmt.executeQuery();
//System.out.print(rs.getString("cid"));
while(rs.next()){
check = true;
System.out.print(rs.getString("cid"));
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) {
//stmt.close();
}
}
return check;
}
Second try on a simpler query:
public List<Object> showTable() {
List<Object> result = new ArrayList<Object>();
String name = "bob";
try
{
PreparedStatement preStatement = con.prepareStatement("select total from test where name = ?");
preStatement.setString(1, name);
ResultSet rs1 = preStatement.executeQuery();
while(rs1.next()){
System.out.println("there");
System.out.println(rs1.getInt("total"));
}
}
catch (SQLException ex)
{
System.out.print("Message: " + ex.getMessage());
}
return result;
}
Remove the quotes around the column name.
String query = "select "+cid+" from customer where password = '"+password+"'";
You've not mentioned which database you're working with but many databases like Oracle change the column case to upper case unless they're quoted. So, you only quote table columns if that's how you had created them. For example, if you had created a table like
CREATE TABLE some_table ( 'DoNotChangeToUpperCase' VARCHAR2 );
Then you would have to select the column with quotes as well
SELECT 'DoNotChangeToUpperCase' FROM some_table
But, if you didn't create the table using quotes you shouldn't be using them with your SELECTs either.
Make sure you are not closing the ResultSet before you are trying to use it. This can happen when you return a ResultSet and try to use it elsewhere. If you want to return the data like this, use CachedRowSet:
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(ResultSet);
CachedRowSet is "special in that it can operate without being connected to its data source, that is, it is a disconnected RowSet object"
Edit: Saw you posted code so I thought I add some thoughts. If that is your ACTUAL code than the reason you are not getting anything is because the query is probably not returning anything.
String query = "select '"+cid+"' from customer where password = '"+password+"'";
This is wrong, for two reasons. 1) If you are using prepared statements you should replace all input with '?' so it should look like the following:
String query = "select name from customer where password = ?";
Then:
PreparedStatement prepStmt = con.prepareStatement(query);
prepStmt.setString(1, password);
ResultSet rs = prepStmt.executeQuery();
2)
System.out.print(rs.getString("cid"));
Here are are trying to get the column named "cid", when it should be the name stored in cid. You should actually never be letting the user decide what columns to get, this should be hardcoded in.

Delete row from database

I have a database table with the following layout:
Columns:
_________________________
id | user_name | password
But I can't delete a specified row by using the username.
I am receiving the following error:
MySQLSyntaxErrorException: Unknown column 'vipin' in 'where clause'
vipin is a value within the table.
Can anyone help me?
public void deleteFclty() {
PreparedStatement stmt = null;
ResultSet rs = null;
String username = removeText.getText();
ArrayList<String> values = new ArrayList();
String qry = "SELECT user_name From users ";
try {
stmt = (PreparedStatement) connection.prepareStatement(qry);
rs = stmt.executeQuery();
while (rs.next()) {
values.add(0, rs.getString(("user_name")));
System.out.println(values);
}
} catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
if (values.contains(username)) {
username = removeText.getText();
Boolean isAdmin = false;
try {
System.out.println(username);
preparedStatement = (PreparedStatement) connection.prepareStatement("DELETE FROM users WHERE user_name=" + username + "");
preparedStatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
Util.showErrorMessageDialog(username + " is not found.Please try again.");
}
}
Since you're already using PreparedStatement, use it right and pass the username as parameter instead of just concatenating the Strings:
//no need to use a cast here
preparedStatement = connection.prepareStatement(
//note the usage of ? instead of concatenating Strings
"DELETE FROM users WHERE user_name=?");
//setting the first parameter in the query string to be username
preparedStatement.setString(1, username);
preparedStatement.executeUpdate();
Using this, you won't have any concatenation problems and what's better, your code won't be prone to SQL Injection.
Not directly related to your problem, but it would be better if you move the code to execute INSERT, UPDATE and DELETE statements to a single method.
public void executeUpdate(Connection con, String query, Object ... params)
throws SQLException {
PreparedStatement pstmt = con.prepareStatement(query);
if (params != null) {
int i = 1;
for(Object param : params) {
pstmt.setObject(i++, param);
}
}
pstmt.executeUpdate();
pstmt.close();
}
So your code would be dramatically reduced to:
String deleteSQL = "DELETE FROM users WHERE user_name=?";
executeUpdate(deleteSQL, username);
Note that you can create a new method based on this approach to execute SELECT statements.
Also, don't forget to close your resources. This also can be dramatically reduced using a method like this:
public void closeResource(AutoCloseable res) {
try {
if (res != null) {
res.close();
}
} catch (Exception e) {
//handle this exception...
//basic example, not meant to be used in production!
e.printStacktrace(System.out);
}
}
Note that Connection, Statement (and its children PreparedStatement and CallableStatement) and ResultSet interfaces already extend from AutoCloseable.
You haven't quoted the username you're inserting into the query, so it's being treated as a reference to a field name:
DELETE FROM users WHERE user_name='"+username+"'"
^-- ^--
Note: building queries like this leaves you open to SQL injection attacks. Used prepared statements and placeholders instead.
I think you might need some quotes round the username in the where clause
connection.prepareStatement("DELETE FROM users WHERE user_name='"+username+"'");
You are going to want to quote your Strings
"DELETE FROM users WHERE user_name="+username+"";
Like this:
"DELETE FROM users WHERE user_name='" + username + "'";
What would be better is just using PreparedStatement as it was intended:
"DELETE FROM users WHERE user_name = ?";
And then using:
preparedStatement.setString(1, username);
before calling executeUpdate
The query should look like this
preparedStatement = (PreparedStatement) connection.prepareStatement("DELETE FROM users WHERE user_name='"+username+"'");
Note : Mind the single quotes used for user_name='"+username+"'"

Categories