I tried to select some data from a MYSQL database tab and insert them into another MYSQL database table.
This is my servlet code
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
ArrayList al = null;
int size = 0;
size = AcceptDao.getData(name);
if (size>0) {
out.println("<script type=\"text/javascript\">");
out.println("alert('Successfully Employee Added');");
out.println("</script>");
} else {
out.println("<script type=\"text/javascript\">");
out.println("alert('Try Again');");
out.println("</script>");
}
}
and here is my java code to do select and insert data.
public static int getData(String Uname) {
ArrayList al = null;
int status = 0;
String name = null;
String role = null;
String pass = null;
try {
Connection con = ConnectionProvider.getCon();
String query = "SELECT noty_name,noty_user_role,noty_pass FROM notification WHERE noty_name='" + Uname + "'";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
al = new ArrayList();
while (rs.next()) {
name = rs.getString("noty_name");
role = rs.getString("noty_user_role");
pass = rs.getString("noty_pass");
}
PreparedStatement ps = con.prepareStatement("INSERT INTO employee (name,user_role,pass) values(?,?,?)");
ps.setString(1, name);
ps.setString(2, role);
ps.setString(3, pass);
status = ps.executeUpdate();
} catch (Exception e) {
}
return status;
}
this isn't work properly. this code doesn't do select and insert. What is the wrong with this code.
Please note that the code part for "insert" is outside the loop. So only the last data in the loop will be inserted, if available.
Moreover there is no need of while(rs.next) loop. you can use if(rs.next) condition if you are sure that you be passing a unique name in the request.
while (rs.next()) {
name = rs.getString("noty_name");
role = rs.getString("noty_user_role");
pass = rs.getString("noty_pass");
}
/* The Below part is wrong */
PreparedStatement ps = con.prepareStatement("INSERT INTO employee (name,user_role,pass) values(?,?,?)");
ps.setString(1, name);
ps.setString(2, role);
ps.setString(3, pass);
status = ps.executeUpdate();
Instead use this below code
public static int getData(String Uname) {
ArrayList al = null;
int status = 0;
String name = null;
String role = null;
String pass = null;
try {
Connection con = ConnectionProvider.getCon();
String query = "SELECT noty_name,noty_user_role,noty_pass FROM notification WHERE name='" + Uname + "'";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
al = new ArrayList();
PreparedStatement ps = con.prepareStatement("INSERT INTO employee (name,user_role,pass) values(?,?,?)");
while (rs.next()) {
name = rs.getString("noty_name");
role = rs.getString("noty_user_role");
pass = rs.getString("noty_pass");
ps.setString(1, name);
ps.setString(2, role);
ps.setString(3, pass);
status = ps.executeUpdate();
}
} catch (Exception e) {
}
return status;
}
Related
I have a login servlet where I have a login query in my post method from the query I am getting username, password, company name and ID
I am storing all this values in a variable like
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String companyDB,nameDB,idDB;
try {
con = DBConnection.createConnection();
statement = con.createStatement();
String sql = " SELECT MT_USERS.MT_USERS_VCLOGINCODE AS USERID, MT_USERS.MT_USERS_VCUSERPASSWORD AS PASSWORDID, MT_USERS.MT_USERS_VCUSERNAME AS NAME, (SELECT MT_DISTRIBUTR_VCDISTRIBUTRNAME FROM MT_DISTRIBUTR WHERE MT_DISTRIBUTR_VCDISTRIBUTRCODE = MT_USERS.MT_DISTRIBUTR_VCDISTRIBUTRCODE) AS COMPANYNAME ,(SELECT mt_distributr_vcdistributrcode FROM mt_distributr WHERE MT_DISTRIBUTR_VCDISTRIBUTRCODE = MT_USERS.MT_DISTRIBUTR_VCDISTRIBUTRCODE) AS ID FROM MT_USERS WHERE MT_USERS_VCLOGINCODE='admin' AND MT_USERS_VCUSERPASSWORD ='admin'";
resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
companyDB = resultSet.getString("COMPANYNAME");
nameDB = resultSet.getString("name");
idDB = resultset.getString("ID");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Now I have an another class where I am writing a query and in that query I want to use idDB like
My new class is
public class Outlet {
Connection con = null;
Statement statement = null;
ResultSet resultSet = null;
public List<String> getoutlet() throws ClassNotFoundException, SQLException {
List<String> list = new ArrayList<String>();
con = DBConnection.createConnection();
statement = con.createStatement();
try {
ResultSet resultSet = statement.executeQuery("select * from ecustomer where CUSTOMERIDENTIFIER in(select CUSTOMERIDENTIFIER from mt_distributrol where mt_distributr_vcdistributrcode = 'AAAA'");
while (resultSet.next()) {
list.add(resultSet.getString("CUSTOMERDESCRIPTOR"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
Where mt_distributr_vcdistributrcode = 'AAAA'" at the place of 'AAAA' I have to pass a variable which has the value of idDB
You may use a prepared statement here:
String sql = "SELECT CUSTOMERDESCRIPTOR FROM ecustomer WHERE CUSTOMERIDENTIFIER IN (";
sql += "SELECT CUSTOMERIDENTIFIER FROM mt_distributrol ";
sql += "WHERE mt_distributr_vcdistributrcode = ?)");
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "AAAA");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(resultSet.getString("CUSTOMERDESCRIPTOR"));
}
I actually find that MkYong does a good job of explaining prepared statements in Java, see here, but any good documentation is a good place to start looking. And see Oracle Tutorial.
I have exactly same function in both Main method and other method JDBC connection is working fine. If I call the other function it throws error java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/wine:
I have included MySql Driver in library [Netbeans];
processRequest method:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String process = (String) request.getParameter("process");
String name = (String) request.getParameter("process");
String phone=(String) request.getParameter("phone");
String email = (String) request.getParameter("email");
String pwd = (String) request.getParameter("pwd");
PrintWriter out = response.getWriter();
out.println("Hello");
signup(out,process,name,email,phone,pwd);
}
signup method:
private static int signup(PrintWriter out,String process,String name,String email,String phone,String pwd){
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wine", "root", "");
out.println("Process Not Found");
if (process == "signup") {
String query = "INSERT INTO user(name,phone,email,password,role) VALUES(?,?,?,?,1)";
stmt = con.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, phone);
stmt.setString(3, email);
stmt.setString(4, pwd);
stmt.execute();
} else {
out.println("Process Not Found");
}
} catch (SQLException e) {
// do something appropriate with the exception, *at least*:
out.println(e);
e.printStackTrace();
return 0;
}
return 1;
}
Main Method :
public static void main(String[] args) {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String process = "signup";
String name = "Test";
String phone="45885";
String email = "Test#gmail.com";
String pwd = "dkjsdh";
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wine", "root", "");
if (process == "signup") {
String query = "INSERT INTO user(name,phone,email,password,role,status) VALUES(?,?,?,?,1,1)";
stmt = con.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, phone);
stmt.setString(3, email);
stmt.setString(4, pwd);
stmt.execute();
} else {
System.out.println("Process Not Found");
}
} catch (SQLException e) {
// do something appropriate with the exception, *at least*:
System.out.println(e);
e.printStackTrace();
}
}
There are two options that can be tried:
Class.forName("com.mysql.jdbc.Driver").newInstance() //older bug
and
Class.forName("com.mysql.jdbc.Driver");
In the comment I pasted the older bug solution when I meant to paste the second one.
Either way I am glad that it worked out for you
Please help me fix the error in this program. The problem is, even if I use the correct username and password, I can't create a verified login.
public class LoginDao {
public static boolean CheckUser(String Username,String Password)
{
boolean st =false;
String dbUsername, dbPassword;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DBConnection.getConnection();
String qry ="select *user where Username=? and Password=?";
PreparedStatement pst = con.prepareStatement(qry);
//pst.setString(1, Username);
//pst.setString(2, Password);
pst.executeQuery(qry);
ResultSet rs = pst.getResultSet();
while(rs.next()){
dbUsername = rs.getString("Username");
dbPassword = rs.getString("Password");
if(dbUsername.equals(Username) && dbPassword.equals(Password)){
System.out.println("Welcome");
st = true;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return st;
}
}
Check your SQL query? You are missing a FROM before * and user. Also you need to set the parameters when using a PreparedStatement, you have them commented out.
UPDATE
Try this:
public class LoginDao {
public static boolean CheckUser(final String username, final String password) {
final String qry ="SELECT * FROM user WHERE Username=? AND Password=?";
Connection con = null;
PreparedStatement pst;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DBConnection.getConnection();
pst = con.prepareStatement(qry);
pst.setString(1, username);
pst.setString(2, password);
pst.executeQuery(qry);
rs = pst.getResultSet();
// Notice I changed the 'while' by 'if'
if (rs.next()) {
return (username.equals(rs.getString("Username")) && password.equals(rs.getString("Password")));
}
} catch (final Exception e) {
e.printStackTrace();
} finally {
// close/release (database resources) 'con', 'pst', 'rs' here
}
return false;
}
}
Can someone tell me why this fails at the ps.excuteUpdate statement? It seems to work and changes the data in the database but it fails at the execute statement which won't let it execute the other two ps1 and ps2 statements.
buyStock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
BuyStock();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
public void BuyStock() throws SQLException, IOException{
Connection conn = null;
PreparedStatement ps = null;
PreparedStatement ps1 = null;
PreparedStatement ps2 = null;
int i = 0;
String username = UserLoginInfo.userEmail;
int bank = 75000;
String string1= "goog";
int shares = 25;
conn = ConnectionManager.getConnection();
if (i == 0) {
ps = conn.prepareStatement("UPDATE L1_Standings SET BANK = ? WHERE EMAIL = '" + username + "'");
ps1 = conn.prepareStatement("UPDATE L1_Stocks SET TICKER_SYMBOL = ? WHERE EMAIL = '" + username + "'");
ps2 = conn.prepareStatement("UPDATE L1_Stocks SET NUM_SHARES = ? WHERE EMAIL = '" + username + "'");
ps.setInt(1, bank);
ps1.setString(1, string1);
ps2.setInt(1, shares);
ps.executeUpdate();
ps1.executeUpdate();
ps2.executeUpdate();
ps.close();
ps1.close();
ps2.close();
} else {
System.out.println("False");
}
How can I detect the empty result set sending from MySQL if there is no possible result.
Just check if ResultSet#next() returns true. E.g.
public boolean exist(String username, String password) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean exist = false;
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT id FROM user WHERE username = ? AND password = MD5(?)");
statement.setString(1, username);
statement.setString(2, password);
resultSet = statement.executeQuery();
exist = resultSet.next();
} finally {
close(resultSet, statement, connection);
}
return exist;
}
which you can use like follows
if (userDAO.exist(username, password)) {
// Proceed with login?
} else {
// Show error?
}
Alternatively, you could also let it return a fullworhy User or null if there's none. E.g.
public User find(String username, String password) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
User user = null;
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT id, username, email, dateOfBirth FROM user WHERE username = ? AND password = MD5(?)");
statement.setString(1, username);
statement.setString(2, password);
resultSet = statement.executeQuery();
if (resultSet.next()) {
user = new User(
resultSet.getLong("id"),
resultSet.getString("username"),
resultSet.getString("email"),
resultSet.getDate("dateOfBirth"));
}
} finally {
close(resultSet, statement, connection);
}
return user;
}
with
User user = userDAO.find(username, password);
if (user != null) {
// Proceed with login?
} else {
// Show error?
}