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.
Related
I would like to ask how to make Connection con = getConnection(); becaome a primer or main variable so that it would not connect to SQL database every function made. Because as you can see on my codes, every function/class has Connection con = getConnection(); so it connects to the database every function. It makes my program process slowly. Please help thank you.
package march30;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
public class sqltesting {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
get();
}
public static void lookup() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename where id=6");
ResultSet result = statement.executeQuery();
if (result.next()) {
System.out.println("First Name: " + result.getString("first"));
System.out.println("Last Name: " + result.getString("last"));
}
else {
System.out.println("No Data Found");
}
} catch (Exception e) {}
}
public static ArrayList<String> get() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename");
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while (result.next()) {
System.out.print(result.getString("first"));
System.out.print(" ");
System.out.println(result.getString("last"));
array.add(result.getString("last"));
}
System.out.println("All records have been selected!");
System.out.println(Arrays.asList(array));
return array;
} catch (Exception e) {System.out.println((e));}
return null;
}
public static void update() throws Exception{
final int idnum = 2;
final String var1 = "New";
final String var2 = "Name";
try {
Connection con = getConnection();
PreparedStatement updated = con.prepareStatement("update tablename set first=?, last=? where id=?");
updated.setString(1, var1);
updated.setString(2, var2);
updated.setInt(3, idnum);
updated.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Update Completed");
}
}
public static void delete() throws Exception{
final int idnum = 7;
try {
Connection con = getConnection();
PreparedStatement deleted = con.prepareStatement("Delete from tablename where id=?");
deleted.setInt(1, idnum);
deleted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Delete Completed");
}
}
public static void post() throws Exception{
final String var1 = "Albert";
final String var2 = "Reyes";
try {
Connection con = getConnection();
PreparedStatement posted = con.prepareStatement("INSERT INTO tablename (first, last) VALUES ('"+var1+"', '"+var2+"')");
posted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Insert Completed");
}
}
public static void createTable() throws Exception {
try {
Connection con = getConnection();
PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS tablename(id int NOT NULL AUTO_INCREMENT, first varchar(255), last varchar(255), PRIMARY KEY(id))");
create.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Function Completed");
}
}
public static Connection getConnection() throws Exception{
try {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://xxxxxxxx.amazonaws.com:3306/pointofsale";
String username = "xxxxx";
String password = "xxxxxx";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}
To solve your problem you need to store a Connection object in your sqltesting class as a class member. You then need to reference the Connection object instead of getConnection(). It's also worth mentioning that Connection is a AutoClosable object so you need to close this resource when you're done with it, I.E; on application disposal. You also might want to consider using a connection pooling API like Hikari or C3P0 so you can open and close connections when you need them instead of having 1 open for a long time.
class SQLTesting {
private final Connection connection;
public SQLTesting(Connection connection) {
this.connection = connection;
}
public SQLTesting() {
this(getConnection());
}
// other methods
private Connection getConnection() {
// your method to create connection, rename to createConnection maybe.
}
}
I am trying to output the first column (nameID) of my table (StudentInfo) in my database. But the statement.executeQuery is not working and ResultSet.next() is false.
Java NetBeans program
Calls sqlite database
Uses "jdbc:sqlite:ProjectWeekDB.sqlite" as url
private static Connection connection = null;
private static PreparedStatement stmt = null;
private static Statement statement = null;
private static ResultSet results = null;
public static void createNewDatabase() {
String sqlData = "SELECT * FROM StudentInfo";
String url;
try {
connection = DriverManager.getConnection(url);
if (connection != null) {
statement = connection.createStatement();
stmt = connection.prepareStatement(sqlData);
statement.executeUpdate(sqlData);
results = statement.executeQuery(sqlData);
while (results.next()) {
print(results.getInt("nameID"));
}
stmt.close();
results.close();
}
} catch (SQLException e) {
print(e.getMessage());
}
}
public static void main(String[] args) {
createNewDatabase();
}
It just prints out BUILD successful without actually displaying the first column in the database.
I'm trying to set up JDBC but I'm getting this error.
I tried adding the dependency in pom.xml and even jar file nothing works. I tried the methods mentioned in previous questions, nothing works.
public class FilmLength {
public static void main(String[] args) throws SQLException {
Connection dbCon = null;
PreparedStatement st = null;
ResultSet rs = null;
String url = "jdbc:mysql//localhost:3306/sakila";
String username = "devuser";
String password = "Demo#123";
String query = "select * from film ";
try {
Class.forName("com.mysql.jdbc.Driver");
dbCon = DriverManager.getConnection(url,username,password);
st = dbCon.prepareStatement(query);
rs = st.executeQuery();
while(rs.next()) {
String title = rs.getString(1);
System.out.println(title);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
dbCon.close();
st.close();
rs.close();
}
}
}
Instead of
String url = "jdbc:mysql//localhost:3306/sakila";
it should be
String url = "jdbc:mysql://localhost:3306/sakila";
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
I've got 2 file in my java project : MysqlConnect and Main .
I want to run query from Main class.It's possible?
This is MysqlConnect file:
public class MysqlConnect {
public Connection conn = null;
public String url = "jdbc:mysql://localhost:3306/";
public String dbName = "jdbctutorial";
public String driver = "com.mysql.jdbc.Driver";
public String userName = "birthday";
public String password = "123456";
public Statement stmt;
public String query = "";
public int rs;
public void crearedatabase() {
try {
Class.forName(driver).newInstance();
conn = DriverManager
.getConnection(url + dbName, userName, password);
// System.out.println("Connected to the database");
Statement stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("Baza de date nu a fost creata");
}
}
public void executeSql() {
try {
rs = stmt.executeUpdate(query);
} catch (Exception e) {
System.out.println("Mysql Error");
}
}
}
And this is the Main file:
public class Main {
public static void main(String[] args) throws SQLException
{
MysqlConnect sqlconnect = new MysqlConnect();
sqlconnect.crearedatabase();
sqlconnect.query="INSERT INTO `jdbctutorial`.`persons` (`id`, `nume`, `prenume`, `data`) VALUES (NULL, 'xxxx', 'xxxx', '1990-12-12');";
sqlconnect.executeSql();
}
}
The error(Exception) is on the MysqConnection at the try/catch
rs = stmt.executeUpdate(query);
You assign statement object to a local variable named stmt instead of the object field with the same name.
Replace this
Statement stmt = conn.createStatement();
With this:
this.stmt = conn.createStatement();
this is not necessary here, but it's a good practice to have it there.