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) {}
}
}
Related
I'm working on a javafx project where a user can register as either a driver or a client. For this, I created 3 tables in a mysql database, a general one for all users and 2 specific ones for the drivers and the clients. When a new user registers he is placed in the database_user table and, depending on his selected role, he is also placed in either database_client or database_driver. The problem is that the specific tables should have a column storing the primary key value (autoincrement value) from the general table, for easier communication.
public static void registerClient(ActionEvent event, String username, String password, String role, String name, int age, String gender, String email)
{
/*
these variables are the connections to the mysql database
*/
Connection connection = null;
PreparedStatement psInsert = null;
PreparedStatement psInsertClient = null;
PreparedStatement psCheckUserAlreadyExists = null;
//PreparedStatement psCheckEmailAlreadyUsed = null;
ResultSet resultSet = null;
try{
/*
this will attempt to establish a connection with the db
*/
connection = DriverManager.getConnection("jdbc:mariadb://lazarov.go.ro:3306/RideShare", "root", "chocolate");
psCheckUserAlreadyExists = connection.prepareStatement("SELECT * FROM database_user WHERE username = ?");
psCheckUserAlreadyExists.setString(1, username);
//psCheckEmailAlreadyUsed = connection.prepareStatement("SELECT * FROM user_database WHERE email = ? ");
//psCheckEmailAlreadyUsed.setString(7, email);
resultSet = psCheckUserAlreadyExists.executeQuery();
/*
check if the resultSet is empty
if true => username already taken => notify user about this
*/
if(resultSet.isBeforeFirst())
{
System.out.println("Username already taken!");
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("User already exists!");
alert.showAndWait();
}
else
{
psInsert = connection.prepareStatement("INSERT INTO database_user (username, password, role, name, age, gender, email) VALUES (?, ?, ?, ?, ?, ?, ?)");
psInsert.setString(1, username);
psInsert.setString(2, password);
psInsert.setString(3, role);
psInsert.setString(4, name);
psInsert.setInt(5, age);
psInsert.setString(6, gender);
psInsert.setString(7, email);
psInsert.executeUpdate();
ResultSet rs = null;
psInsert = connection.prepareStatement("SELECT max(user_id) FROM database_user");
rs = psInsert.executeQuery();
// driver specific
int userId = resultSet.getInt("max(user_id)"); // this is where the error occurs
//Connection connectionDriver = null;
psInsertClient = connection.prepareStatement("INSERT INTO database_client (user_id, ride_requested, location, destination, corresponding_driver_id) VALUES (?, ?, ?, ?, ?)");
psInsertClient.setInt(1, userId);
psInsertClient.setBoolean(2, false);
psInsertClient.setString(3, null);
psInsertClient.setString(4, null);
psInsertClient.setInt(5, 0);
changeScene(event, "client.fxml", "RideShare - Client", username, role, name, age, gender, email);
}
}catch (SQLException e)
{
e.printStackTrace();
}finally {
/*
close db connections to avoid memory leaks
*/
if(resultSet != null)
{
try{
resultSet.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
if(psCheckUserAlreadyExists != null)
{
try{
psCheckUserAlreadyExists.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
if(psInsert != null)
{
try {
psInsert.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
if(psInsertClient != null)
{
try {
psInsertClient.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
if(connection != null)
{
try{
connection.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
If I try to create a new user, the user is added in the database_user correctly, but throws the error "wrong row position" when trying to store it in the "database_client" as well. How can I successfully get the last autoincremented value from the general table?
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
I am pretty new to Java so I'm working on a project to develop my knowledge with databases and Java.
I have figured out how to add queries into the database but now I'm getting errors when trying to print them out.
Assume I already have everything that's necessary imported in such as the scanner and sql statements
Here is my connection class which is named MainClass:
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/testTable";
String username = "placeholder";
String password = "placeholder";
Class.forName(driver);
Connection conn = Driver Manager.getConnection(url, username, password);
return conn;
}
Now in a different class if the user types !lookup and a word I want the definition of that word to be retrieved from the table whose name is dictionary and columns are word, definition:
String userSearch = user_input.next();
String[] userSearchSplit = userSearch.split(" ", 3);
if (userSearchSplit[0].equals("!lookup")) {
try {
conn = MainClass.getConnection();
String query = "select definition from dictionary where word=" + userSearchSplit[1];
ResultSet result = pstmt.executeQuery(query);
while (result.next()) {
String definition = result.getString("definition");
System.out.println(definition);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
At the end of all this when I try to look up a word I put in the table before running I get:
java.lang.NullPointerException
Check if your user_input is null?
I am assuming your code:
ResultSet result = pstmt.executeQuery(query);
as
Statement pstmt = conn.createStatement();
ResultSet result = pstmt.executeQuery(query);
Or it could be that you have not initialized the pstmt properly
I am trying to validate a database (phpMyadmin) using Username and Password. I need to search in all the tables (25 tables in my database) for checking if the given username and password are present (Authentication) or not. Can anyone provide the query to search entire table using the given username and password?
Below is my code
public class Dbclass {
/**
* #param args
*/
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
ResultSetMetaData metaData = null;
String DB_URL="com.mysql.jdbc.Driver";
String USER="java";
String PASS="redhat";
String username;
String password;
ResultSet rs;
public ResultSet dbConnection(String query)
{
//STEP 2: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
try {
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
Statement stmt = conn.createStatement();
//sql = "SELECT username,password FROM Employees";
rs = stmt.executeQuery(query);
while(rs.next()){
//Retrieve by column name
username = rs.getString("user_name");
password = rs.getString("password");
//Display values
System.out.print("User_name: " + username);
System.out.print(",Password: " + password);
}
Authentication obj=new Authentication();
obj.userLogin(username,password);
//STEP 6: Clean-up environment
//rs.close();
//return rs;
stmt.close();
conn.close();
} catch (SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException es) {
//TODO Auto-generated catch block
es.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(conn!=null){
conn.close();
}
if (rs != null) {
rs.close();
}
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
return rs;
}
}
I guess you're looking for a where clause. Something like below.
SELECT username,password FROM Employees where username='usernm' and password='pwd'
If required, you can add UNION to merge more such queries, but not recommended due to performance issues.
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