can't able to access ms-acess database 2010 - java

Can anyone help me , why i cant be able to access ms-access database.
pls find fault in my code.
protected String processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
int e_no=Integer.parseInt(request.getParameter("enrollment_no"));
String branch=request.getParameter("branch");
String sem=request.getParameter("semester");
String f_name=request.getParameter("first_name");
String l_name=request.getParameter("last_name");
String email=request.getParameter("email");
String pass=request.getParameter("password");
Connection con;
Statement stm;
try {
String driver="sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db="jdbc:odbc:practicedb";
con=DriverManager.getConnection(db);
stm=con.createStatement();
String query="insert into studenttbl values='"+e_no+"','"+branch+"','"+sem+"','"+f_name+"','"+l_name+"','"+email+"''"+pass+"'";
stm.executeUpdate(query);
out.println("Database Successfuly added");
}
catch(ClassNotFoundException | SQLException e) {
}
}
return null;
}

Edit:
String database = "FILE PATH ON YOUR LAPTOP";
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + database + ";DriverID=22;READONLY=true";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, "", "");
java.sql.Statement stm = con.createStatement();
Also, add a catch statement just before the return null.
As pointed by #jpw, you might want to double check your insert query. It should be something like this:
String query="insert into studenttbl values('"+e_no+"','"+branch+"','"+sem+"','"+f_name+"','"+l_name+"','"+email+"''"+pass+"')";

Related

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

How to query insert postgresql in servlet

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

Name [dsjndi] is not bound in this Context. Unable to find [dsjndi]

i'm trying to use jdbc connection pool, for that i create IntialContext obj and datasource obj, and give "dsjndi" as parameter of lookup method of initialcontext, but when i run my project project it shows ""Name [dsjndi] is not bound in this Context. Unable to find [dsjndi].""
What is the problem can anyone guide me?
Connection con = null;
Statement st = null;
ResultSet rs = null;
ResultSetMetaData rsmd = null;
public void process(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
//general settings
//get print Writer obj
PrintWriter pw = res.getWriter();
//set content type
res.setContentType("text/html");
//read form data
String tableName = req.getParameter("table");
try
{
//get con obj from jdbc con pool
con = makeConnection();
//create Statement obj
st = con.createStatement();
//execute query
rs = st.executeQuery("select * form" +tableName);
//use metadata obj to get db vlaues along with the col names
rsmd = rs.getMetaData();
int cnt = rsmd.getColumnCount();
pw.println("<hmtl><body bgcolor='#ffffa9'>");
pw.println("<center><h3>the details of the table" +tableName);
pw.println("<br><br><table cellsapcing='1' bgcolor='#00ff00'>");
pw.println("<tr bgcolor='#ffffa9'>");
//pritnt col names
for(int col=1;col<=cnt;col++)
{
pw.println("<th>" +rsmd.getColumnLabel(col)+ " &nbsp");
}
pw.println("</tr>");
//print col values
while(rs.next())
{
pw.println("<tr bgcolor='#ffffa9'>");
for(int i=1;i<=cnt;i++)
{
pw.println("<td>" +rs.getString(i)+ " </td>");
}
pw.println("</td>");
}//while
pw.println("<table><br/>");
pw.println("<b>to view another table</b><ahref='index.html'>click here</a>");
pw.println("</body></html>");
}//try
catch(Exception e)
{
e.printStackTrace();
}
}
private Connection makeConnection()
{
Connection con = null;
try
{
//get IntialConetext
InitialContext ic = new InitialContext();
//get data sourse obj
DataSource ds = (DataSource) ic.lookup("DsJndi");
//get jdbc con obj from con pool
con = ds.getConnection();
}//try
catch(Exception e)
{
e.printStackTrace();
}
return con;
}//make Connection
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
process(req,res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
process(req,res);
}
}

simple login form using java and db2 . everything ok but still resultset empty

I am trying to make a simple login form. Every thing is working fine, connection is established, query is executed but ResultSet is still empty so always getting redirected to fail.jsp. No error no warning at all.
Servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("password");
modelclass md = new modelclass();
daoclass dao = new daoclass();
md.setName(name);
md.setPassword(password);
System.out.println("this just before the sql query on the main servlet page");
String sql = "Select * from USERADD where name = ? and password= ?";
String result = dao.guser(md, sql);
if (result.equals("success")) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("fail.jsp");
}
}
This is the DAO class which makes connection.
Data Access code(dao.java):
public class daoclass {
public static String username = "NickNeo";
public static String password = "123123";
public static String driver = "com.ibm.db2.jcc.DB2Driver";
public static String url = "jdbc:db2://localhost:50000/CITYLIFE";
public static Connection con = null;
public static PreparedStatement ps = null;
static {
try {
Class.forName(driver);
System.out.println("before connection");
con = DriverManager.getConnection(url, username, password);
System.out.println("Connection Successfullll......!!!!!!");
} catch(Exception e) {
e.printStackTrace();
}
}
public String guser(modelclass obj, String sql) {
try {
System.out.println("entry into try block");
ps=con.prepareStatement(sql);
ps.setString(1, obj.getName());
ps.setString(2, obj.getPassword());
System.out.println("before query");
ResultSet rs = ps.executeQuery();
System.out.println("query executed");
int i = 0;
while(rs.next()) {
System.out.println("entered into while loop");
++i;
}
if (i >= 1) {
return "success";
} else {
System.out.println("this is inside else of while block");
return "fail";
}
} catch(Exception e) {
e.printStackTrace();
}
System.out.println("this is the most outer fail statement");
return "fail";
}
}
the rs is always empty. tried many things but still getting rs as empty. please help

simple data comparison with MySQL, nullpointerexception

I'm currently being thrown into the depths by my school and they are expecting me to program a simple login form using sql. They have given us brief examples on how they use JDBC and what it all is, but haven't really explained step by step how to use it on our own. Therefore i have snatched a bit of code from an example but i'm unable to get it working. I keep receiving an nullpointerexception and i can't figure out why :(
Here's the connection class:
package Database;
import java.sql.*;
public class MySQLConnection {
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String DBURL = "jdbc:mysql://localhost/corendon";
public static final String DBUSER = "root";
public static final String DBPASS = "simplepass";
private ResultSet result = null;
private int affectedRows = -1;
Connection conn = null;
public void startConnection() {
try {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (Exception e) {
}
}
public void closeConnection() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (Exception e) {
}
conn = null;
}
public ResultSet performSelect(PreparedStatement prdstmt) throws SQLException {
result = prdstmt.executeQuery();
return result;
}
public int performUpdate(PreparedStatement prdstmt) throws SQLException {
affectedRows = prdstmt.executeUpdate();
return affectedRows;
}
public Connection getConnection() {
return conn;
}
}
And here is the method i'm getting the exception in (in a different class):
MySQLConnection conn = new MySQLConnection();
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
conn.startConnection();
prdstmt = conn.getConnection().prepareStatement(query);
prdstmt.setInt(1, id);
prdstmt.setString(2, pass);
rs = conn.performSelect(prdstmt);
while (rs.next()){
String tempPass = rs.getString("password");
int tempId = rs.getInt("id");
}
if(conn != null){
conn.closeConnection();
}
}
I'm getting the nullpointerexception on line:
prdstmt = conn.getConnection().prepareStatement(query);
Why does it throw an exception there, but not when i start the connection and also how do i solve this? Thanks in advance.
When you call startConnection(), you are throwing an Exception
public void startConnection() {
try {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (Exception e) {
//An exception occurs here, but you don't do anything about it
}
}
Therefore, when you call getConnection(), the conn variable is still null, which is throwing the NullPointerException.
Either make startConnection() throw an exception so that you're forced to deal with it (this is usually how most JDBC drivers work anyway), or check to see if the conn variable is null before you start using it.
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
conn.startConnection();
if (conn.getConnection() == null) {
throw new SQLException("Connection is null!");
}
Or (what I think would personally be better)
public void startConnection() throws Exception {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
}
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
try {
conn.startConnection();
} catch (Exception e) {
throw new SQLException(e);
}
Also as a tip, you should probably avoid declaring your classes as the same name of other classes you are using. This is all happening in your own MySQLConnection class, but that could be confusing with the actual com.mysql.jdbc.MySQLConnection class.

Categories