I can't execute the update query on JDBC with where clause. I want to execute the query by concatenating some variables.
protected void updateEmail(String Email, String Username) {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", "");
String query = "update access set email=" + Email + " where username=" + Username;
Statement st = conn.createStatement();
st.executeUpdate(query);
} catch (SQLException ex) {
System.out.println(ex);
} finally {
try {
conn.close();
} catch (SQLException ex) {
}
}
}
It says:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'bhusal1' in 'where clause'
String should be between two quotes 'name' instead of your way you have to use PreparedStatement instead to avoid syntax error or SQL Injection :
String query = "update access set email=? where username=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, email);
ps.setString(2, name);
ps.executeUpdate();
This is most likely a problem with concatenation of the request. The approach you use is extremely bad and can cause any problems (including security).
To avoid problems, use PrepareStatement when you need to submit sql query parameters.
Here's an example that should solve your problem:
void updateEmail(String email,String username) {
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", "")) {
String query = "update access set email = ? where username = ?";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, email);
statement.setString(2, username);
statement.executeUpdate();
}
}
catch (SQLException e) {
System.out.println(e);
}
}
You should put your variables email and username between quotes in the where clause to be able to do the update query
Related
I have this code
public PreparedStatement InsertDepartmentQuery() {
try {
ps = conn.prepareStatement("INSERT INTO department (DepartmentNo,DepartmentName,DepartmentLocation) VALUES (?,?,?)");
}
catch(SQLException e) {
e.printStackTrace();
}
return ps;
}
and
public void InsertyTuple() {
int a = -1;
ps = InsertDepartmentQuery();
try {
ps.setInt(1, DeptNo);
ps.setString(2, DeptName);
ps.setString(3, DeptLocation);
a = ps.executeUpdate();
}
catch(SQLException e) {
e.printStackTrace();
}
System.out.println(a);
}
and
Department test = new Department(106, "TB_1", "Tabuk");
test.InsertyTuple();
It executes fine in Eclipse, even a select query in there returns the expected results. But none of the inserts are showing up in MySQL Workbench. I tried restarting the connection and it didn't work. Autocommits are on as when I tried to do a manual commit it told me so.
Wrong schema name
Well I found the problem so I'll just leave the answer and feel stupid later.
I had the connection started as
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=CONVERT_TO_NULL", username, password);
when it should've been
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/project?zeroDateTimeBehavior=CONVERT_TO_NULL", username, password);
the "project" replacing "mysql" is the name of my schema in MySQL.
So i got this form that I'm using but I get that error whenever i submit, it says CONNECTION SUCCESSFUL but then it returns the error and never insert nor retrieves anything from the db. I checked the version of the sqlite and everything, can't figure it out.
public class databaseConnection {
public static Connection connection = null;
public static Connection getConnection() throws ClassNotFoundException {
try {
System.out.println("CONNECTING");
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:SoftwareDB.db");
System.out.println("CONNECTION SUCCESSFUL");
} catch (SQLException e) {
System.out.println("ERROR: Connection Failed!");
}
return connection;
}
public static void login(String username, String password, String login) throws ClassNotFoundException {
try {
System.out.println("INSERTING");
try (Statement stmt = getConnection().createStatement()) {
String sql = "INSERT INTO login (username, password) VALUES ('" + username + "', '" + password + "', '" + login + "');";
stmt.execute(sql);
}
getConnection().close();
System.out.println("INSERT SUCCESSFUL");
} catch (SQLException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static ResultSet getLoginDetails(String query) throws SQLException, ClassNotFoundException {
ResultSet rs;
try (PreparedStatement ps = getConnection().prepareStatement(query)) {
rs = ps.executeQuery();
ps.close();
getConnection().close();
}
return rs;
}
public static ResultSet getExistentDetails(String query) throws SQLException, ClassNotFoundException {
ResultSet rs;
try (PreparedStatement ps = getConnection().prepareStatement(query)) {
rs = ps.executeQuery();
getConnection().close();
}
return rs;
}
}
private void loginBtnMouseClicked(java.awt.event.MouseEvent evt) {
if (username.getText().isEmpty() || password.getText().isEmpty()) {
infoLabel.setVisible(true);
username.setText("");
password.setText("");
} else {
try {
databaseConnection.getLoginDetails("SELECT * FROM register WHERE email = '?' AND password = '?'");
String ts = new SimpleDateFormat("dd.MM.yyyy - HH.mm.ss").format(System.currentTimeMillis());
databaseConnection.login(username.getText(), password.getText(), ts);
JOptionPane.showMessageDialog(null, "Login succesful!");
new login().setVisible(true);
infoLabel.setVisible(true);
username.setText("");
password.setText("");
} catch (HeadlessException ex) {
JOptionPane.showMessageDialog(null, "Failed!");
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Output
I believe you have forgotten an important thing: properly preparing your PreparedStatement and opening/closing connections correctly.
Would you try the following rewritten getLoginDetails() method and take inspiration from it for the other methods?
public static ResultSet getLoginDetails(String query, String email, String password) throws SQLException, ClassNotFoundException {
ResultSet rs;
try (Connection conn = getConnection()) {
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1,email);
ps.SetString(2,password);
rs = ps.executeQuery();
// Do something with the ResultSet here or do not close the statement!
}
}
return rs; // should be something else! (as it could be already closed)
}
Then you certainly need to do something with the ResultSet! For example: check that the email/password combination exists in order to validate the login request.
Also, some important remarks and tips:
better check that the connection is valid after initialization using isValid(timeout)
think about a connection pool or at least some ways to reuse your connection(s)
eventually use existing tools (libraries like Apache) for your ORM (Object-Relation Mapping) and DAO (Database Access Object) layers. Actually, that's highly recommended.
closing a PreparedStatement will automatically close the associated ResultSet. Your code does not take that into account. Cf. https://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html
Keep me posted!
I am new to jsp pages and trying to make a login page by checking username and password from the database. Here is the code:
protected void CheckUser(String username, String password)
{
try {
connect();
PreparedStatement preparedStatement = con.PreparedStatement(
"SELECT * Users WHERE username = ? AND password = ?");
preparedStatement.setString(1,username);
preparedStatement.setString(2,password);
ResultSet rs = (ResultSet) preparedStatement.executeQuery();
} catch (Exception e) {
System.out.println("cannot connect");
e.printStackTrace();
}
}
I get the following error for con.PreparedStatement
The method PreparedStatement(String) is undefined for the type Connection
Can anyone help me with this?
Thanks
Edit: Here is my connection function:
static String dbUrl="jdbc:mysql://localhost:3306/Bank";
static String username="root";
static String password="";
static Connection con=null;
public static void connect ()
{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=(Connection) DriverManager.getConnection(dbUrl,username,password);
System.out.println("Connected!");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("not connected");
}
}
You spelled the method wrong Connection#prepareStatement(String sql) throws SQLException.
It should be con.prepareStatement, not con.PreparedStatement.
You have to create a Prepared Statement by doing PreparedStatement preparedStatement = con.prepareStatement("your Query");
You need the from keyword in your Query.
Hence, your code should look like
PreparedStatement preparedStatement = con.prepareStatement("SELECT * from Users WHERE username = ? AND password = ?");
Not sure about other stuff, but your query is wrong considering its not an typo, will throw SQLException.
It should be
"SELECT * FROM Users WHERE username = ? AND password = ?"
^^^^
||||
here
I have a soap web service that is connected to mySQL database. It has two methods, one is insert() and the other is verify(). The first one enables the user to enter data such as name, email and password. It saves the records in the database successfully.
However am having problems with writing the verify method. It has as input parameters, email and password. It must compare the data entered with those stored in the database and return "registered" or "not registered" if it cant find the match in mysql database. Am having problem writing the codes. Could you please help, am new to jdbc and java web services. Am using netbeans.
Thanks a lot.
Here are my codes:
#WebMethod(operationName = "insert")
public String insert(#WebParam(name = "name") String name,
#WebParam(name = "email") String email,
#WebParam(name = "password") String password {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "1234");
PreparedStatement st = con.prepareStatement("insert into register values(?,?,?)");
st.setString(1, name);
st.setString(2, email);
st.setString(3, password);
st.executeUpdate();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return "record inserted";
}
/**
* Web service operation
*/
#WebMethod(operationName = "Verify")
public String CheckUser(#WebParam(name = "email") String email,
#WebParam(name = "password") String password) {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "1234");
If
// problems to write this statement!!! I need to compare the username and password
// with some select * from register where password == #password and email == #email?
return "Registered user";
else
return "Not registered";
}
This example could work (you might have to change column names in the query). Also, you should close the connection in the insert method, in the same way that this example.
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "1234");
PreparedStatement st = con.prepareStatement("select 1 from register where password = ? and email = ? and name = ?");
st.setString(1, password);
st.setString(2, email);
st.setString(3, name);
ResultSet result = st.executeQuery();
if (result.next()) { //.next() returns true if there is a next row returned by the query.
return "Registered user";
} else {
return "Not registered";
}
} catch (Exception e) {
//TODO manage the exception.
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {}
}
}
I'm trying to record String variables into a database in a MySQL statement in Java.
I've read this and this but I couldn't succeed.
Here is my code:
public void registerUser( String userName, String password ) {
try {
String insertQuery = "INSERT INTO Credentials ('11', name, pass) VALUES('11', ?, ?)";
pstmt = connection.prepareStatement(insertQuery);
pstmt.setString(2, userName);
pstmt.setString(3, password);
pstmt.executeUpdate();
// statement.executeUpdate("INSERT INTO Credentials VALUES(3, 'userName', 'password')");
} catch (SQLException e) {
e.printStackTrace();
} finally {
// close the connection when done
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}//END finally
}//END registerUser
As can you see, this code is getting two String values and it should put them into the database. But I can't find the proper solution.
Any ideas?
Thanks.
This:
pstmt.setString(2, userName);
pstmt.setString(3, password);
Needs to be:
pstmt.setString(1, userName);
pstmt.setString(2, password);
You are only setting two variables in your PreparedStatement, so you need to start counting at 1. The integers used in the setter methods need to match up with the question marks in your statement, not the parameter list of the given SQL string.