Simple Java web service connecting to mySql not working [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I decided to try to connect a java client to a mysql db running on wamp.
Can anybody tell me why im getting this runtime problem?
My DBConnect() class
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DbConnect {
private Connection conn;
private Statement statement;
private ResultSet resultset;
public DbConnect(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://xxx.xxx.xxx.xxx:3306/pk","root","");
} catch (Exception e){
System.out.println("Error: " + e);
}
}
public String getData(){
String result ="";
try {
resultset = statement.executeQuery("select * from data_user");
while(resultset.next())
{
result+=resultset.getString("userFirstName");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
My main() class
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
DbConnect conn = new DbConnect();
System.out.println(conn.getData());
}
My error at runtime
Error: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
The last packet sent successfully to the server was 0 milliseconds
ago. The driver has not received any packets from the server.
Exception in thread "main" java.lang.NullPointerException at
DbConnect.getData(DbConnect.java:26) at Main.main(Main.java:8) ERROR:
JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [util.c:840]
}
Offending line
resultset = statement.executeQuery("select * from data_user");

It looks like you didnt instantiate your statement, unless you are missing some code. You need to do something like the following: statement=conn.createStatement();
Take a look at this example

Related

The value of the local variable conn is not used

As I mentioned on the subject, I am facing the warning "The value of the local variable conn is not used"
I clearly used the variable on my coding but it shows me that type of error.
It will be highly appreciated if you can advise me on this.
[CODE]
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class example {
public static void main(String[] ar) {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Success to find Driver");
}catch(ClassNotFoundException e) {
System.err.println("error = Failed to find driver");
}//*Find MYSQL driver
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/class", "root", "****");
System.out.println("Connected to MySql");
} catch (SQLException e) {
System.err.println("error = Failed to Create connection");
}//* Creating Connection
}
}
[RESULT AFTER RUN]
Success to find Driver
error = Failed to Create connection
In your code you have assigned a reference to conn but you are not using that object anywhere, hence the warning.
To get rid of the warning either use it somewhere (maybe do a sysout somewhere) or add the #SuppressWarnings("unused") annotation

Why does executeUpdate() function not work? Give steps to solve in a normal project rather than a maven based project [duplicate]

This question already has an answer here:
Caused by: java.lang.NoSuchMethodError: org.postgresql.core.BaseConnection.getEncoding()Lorg/postgresql/core/Encoding;
(1 answer)
Closed 4 years ago.
CODE:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aaa;
import static aaa.DB.geom;
import static aaa.DB.getConnection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
public static void main(String[] argv) throws SQLException {
try {
Class.forName("org.postgresql.Driver");
// Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " +
"Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/postgres", "postgres",
"abc");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
//Connection conn = getConnection();
connection.setAutoCommit(false);
Statement s = null;
try {
s = connection.createStatement();
} catch (Exception e) {
System.out.println("statmnt connection not works");
}
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ss.executeUpdate();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
String query = "CREATE TABLE COMPANY(ID INT );";
ResultSet r = s.executeQuery(query);
connection.commit();
} else {
System.out.println("Failed to make connection!");
}
}
}
RUN:
-------- PostgreSQL JDBC Connection Testing ------------
PostgreSQL JDBC Driver Registered!
You made it, take control your database now!
Exception in thread "main" java.lang.NoSuchMethodError:
org.postgresql.core.BaseConnection.getPreferQueryMode()Lorg/postgresql/jdbc/PreferQueryMode;
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:151)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:132)
at aaa.JDBCExample.main(JDBCExample.java:69)
C:\Users\Dell\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
QUESTION:Give me steps to solve it since database is connected already! What is the core of the problem?
The problem is that if database postgresql connected then why not insert into database. The tables are also available and seen from netbeans. There needs to be a way to solve this run time exception issue when there is a query execution... So I needed step by step details to make it correct.
A SELECT statements has to be executed using executeQuery(). executeUpdate() is for DML statements like UPDATE, INSERT, or DELETE that don't normally return a ResultSet. Also, a DDL statement like CREATE TABLE can not be executed using executeQuery() you need execute() or executeUpdate() for that.
So your code should be:
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ResultSet rs = ss.executeQuery();
while (rs.next() {
// do something
}
rs.close();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
And:
String query = "CREATE TABLE COMPANY(ID INT );";
s.execute(query);
connection.commit();
You have connection.setAutoCommit(false); and you didnt commit after performing update. You have to commit your transaction in order for changes to apply. You can also setAutoCommit(true);

java.sql.SQLException Path to 'path' does not exist

I am writing this because I created a simple Login GUI App to test sqlite database as I am a student of Database Systems and new to it, I used java through eclipse, whenever I run the Application this message
java.sql.SQLException path to c:user//path does not exist
Error Screenshot
I have searched a lot on google but couldn't find the solution there is a similar question on stackoverflow but there were not enough answer related to my problem, I want to know how to change the code to make the Application work and connect to database?
Any help will be much appreciated.Thanks
Here is the code:
package dbms;
import java.sql.*;
import javax.swing.*;
public class dbConnection {
Connection conn = null;
public static Connection dbConnector(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:‪‪‪C:\\Users\\chusm\\workspace\\DBMS\\SQlite\\DBMS.sqlite");
JOptionPane.showMessageDialog(null, "Connection Successful!!!");
return conn;
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
It looks like you've got some weird whitespace action going on in your url (between "jdbc:sqlite" and "C:"
Please copy paste this exact code in your project and run it (I only removed the weird whitespace, the rest is exactly like your code)
package dbms;
import javax.swing.*;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
public class StackOverflowExample {
Connection conn = null;
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\chusm\\workspace\\DBMS\\SQlite\\DBMS.sqlite");
JOptionPane.showMessageDialog(null, "Connection Successful!!!");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
public static void main(String[] args) {
Connection connection = dbConnector();
}
}

Null Pointer Exception in java servlets pages [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Im very beginner in Java servlets... i have tried to connect servlet with database but NullPointerException
I tried to resolve this problem ,but no luck...
Error is
java.lang.NullPointerException
JDBCServlet.service(JDBCServlet.java:(42)
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.DriverManager;//1
import java.sql.Connection;//2
import java.sql.SQLException;
import java.sql.Statement;//3
import java.sql.ResultSet;//4
public class JDBCServlet extends HttpServlet {
Connection con;
Statement st;
ResultSet rs;
String sql;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("JDBC Servlet Invoked");
//1st step: load JDBC MySql Drivers
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Drivers Loaded");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//2nd Step: create a connection
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/webtech1", "root", "123456");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String sql = "select * from user";
try {
st = con.createStatement();
rs = st.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getInt("id"));
System.out.println(rs.getString("firstName"));
System.out.println(rs.getString("lastName"));
System.out.println(rs.getString("email"));
System.out.println(rs.getString("password"));
System.out.println(rs.getString("createdate"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please put null checks on your con,st,rs objects. And also double check your mysql connection string.
You have initialised String sql twice. One as a property and one as a local variable i.e.
String sql = "select * from user";
Later, you are calling sql (an instance variable) which is indeed of null value, which causes null pointer exception. You just need to remove String declaration from the body of your service method.

JDBC connection error in mysql (ClassNotFoundException) [duplicate]

This question already has answers here:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse
(21 answers)
Closed 7 years ago.
Hey I am new to java and is right now learning about JDBC. Well i have written this code to create a connection to the sql server where my database is located :
import java.sql.*;
public class Mysql
{
public static void getmysqlconnection()
{
try
{
Connection con = null;
Class.forName("com.mysql,jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/EMP","root","password");
System.out.println("connection created");
}
catch(SQLException se)
{
System.out.println("SQl Exception" + se);
}
catch(ClassNotFoundException e)
{
System.out.println("ClassNotFoundException" + e);
}
}
public static void main(String args[])
{
getmysqlconnection();
}
}
But on compiling it is generating the following error :
ClassNotFoundExceptionjava.lang.ClassNotFoundException: com.mysql.jdbc.Driver
It seems you have a typo. The class name is com.mysql.jdbc.Driver not com.mysql,jdbc.Driver (dot instead of a comma). Also make sure the MySQL JDBC driver Jar is in the classpath. Otherwise the ClassNotFoundException is thrown.

Categories