How to query insert postgresql in servlet - java

I need help for my problem about query insert postgresql in servlet and i have a query like this
public void doInsert(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String msisdn = "";
String prog_id = "";
String branch = "";
res.setContentType("text/html");
String result = null;
msisdn =req.getParameter("msisdn");
prog_id =req.getParameter("prog_id");
branch =req.getParameter("branch");
try{
Class.forName("org.postgresql.Driver");
Connection con=DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/mydatabase","username","password");
ps=con.prepareStatement(
"INSERT INTO reg_agent(msisdn, prog_id, branch) VALUES(?, ?, ?");
ps.setString(1, msisdn);
ps.setString(2, prog_id);
ps.setString(3, branch);
int i=ps.executeUpdate();
}
}
catch(Exception ex){
System.out.println("record not found "+ex.getMessage());
}
}
But, the query can't insert to my database in postgresql.
Thanks in advance

Try to log the request params and see if you are getting the requested values in your servlet,
public void doInsert(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String msisdn = "";
String prog_id = "";
String branch = "";
res.setContentType("text/html");
String result = null;
msisdn =req.getParameter("msisdn");
prog_id =req.getParameter("prog_id");
branch =req.getParameter("branch");
System.out.println("MSISDN: "+msisdn);
System.out.println("PRGID: "+prog_id);
System.out.println("BRANCH: "+branch);
try{
Class.forName("org.postgresql.Driver");
Connection con=DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/mydatabase","username","password");
ps=con.prepareStatement(
"INSERT INTO reg_agent(msisdn, prog_id, branch) VALUES(?, ?, ?");
ps.setString(1, msisdn);
ps.setString(2, prog_id);
ps.setString(3, branch);
int i=ps.executeUpdate();
}
}
catch(Exception ex){
System.out.println("record not found "+ex.getMessage());
}
}

Related

inserting string values in oracle DB shows null values in sql developer

i am inserting some values in oracle tabales using jsp, it doesn't give any error/exception while inserting but when i check the record in oracle 11g using sqldeveloper it show null in all fields (it does insert a record with null values)
here my jsp doPost method code
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = String.valueOf(request.getAttribute("username"));
String password = String.valueOf(request.getAttribute("password"));
try {
PreparedStatement preparedStatement = con.prepareStatement("insert into libraryadmin values (?, ?)");
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
int result = preparedStatement.executeUpdate();
PrintWriter out = response.getWriter();
if (result == 1) {
out.print("<h1>USER CREATED</h1>");
} else {
out.print("<h1>ERROR</h1>");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
that output of sqldeveloper
PS: i'm using System user of oracle
Instead of
String username = String.valueOf(request.getAttribute("username"));
String password = String.valueOf(request.getAttribute("password"));
use
String username = String.valueOf(request.getParameter("username"));
String password = String.valueOf(request.getParameter("password"));

How to use a variable value declared in servlet into a new Java class?

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.

How to insert in a table and display the table content on Apache server?

I have database studentdb and table name student in MySQL. what should i do in order to insert the data and fetch complete table from the database. username is "root" and password is also "root".
I want to insert data in table and after that I want to display the table data content.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String email = request.getParameter("email");
String pass = request.getParameter("pass");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/studentdb","root","root");
PreparedStatement ps=con.prepareStatement
("insert into Student values(?,?,?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are sucessfully registered");
}
String query = "SELECT * FROM student";
// create the java statement
Statement st = conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next())
{
String name = rs.getString("name");
String email = rs.getString("email");
String password = rs.getString("pass");
// print the results
System.out.format("%s, %s, %s\n", name, email, password);
}
st.close();
}
catch(Exception se)
{
se.printStackTrace();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}`enter code here`
There are 3 columns in database "name", "email", "pass".

Select from table and insert into another table

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

JDBC:MySql connection is not working in Ajax request -Java

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

Categories