Hello I have this class that contains a actionPerformed to perform a query it looks like this
MysqlConnect db = new MysqlConnect();
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == openKnop) {
try {
db.connectToAndQueryDatabase("test", "root", "root");
System.out.println("connection established");
Statement st = db.createStatement();
String query = "SELECT id, name, job_id, location FROM person WHERE name = 'Tom Swift'";
st.executeQuery(query);
System.out.println("Selected query succesfull");
} catch (SQLException e1) {
e1.printStackTrace();
}
finally {
db.closeCon();
System.out.println("connection closed");
}
}
and my MysqlConnect(); class looks like this
public class MysqlConnect{
protected Connection con;
public void connectToAndQueryDatabase(String database, String username, String password) throws SQLException {
con = null;
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/" + database,
username,
password);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void closeCon() {
con = null;
}
}
but the problem is at the line
Statement st = db.createStatement();
it doesn't work like i've expected. I'm getting a undefined error.. how can I solve this?
The error says that db an reference of 'MysqlConnect ' doesn't have createStatement method. you need a Connection object. Make your connectToAndQueryDatabase to return Connection object
public Connection connectToAndQueryDatabase(String database, String username, String password) throws SQLException {
//your code
return con;
}
and :
Connection conn = db.connectToAndQueryDatabase("test", "root", "root");
System.out.println("connection established");
Statement st = conn.createStatement();
String query = "SELECT id, name, job_id, location FROM person WHERE name = 'Tom Swift'";
st.executeQuery(query);
Related
So i got this form that I'm using but I get that error whenever i submit, it says CONNECTION SUCCESSFUL but then it returns the error and never insert nor retrieves anything from the db. I checked the version of the sqlite and everything, can't figure it out.
public class databaseConnection {
public static Connection connection = null;
public static Connection getConnection() throws ClassNotFoundException {
try {
System.out.println("CONNECTING");
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:SoftwareDB.db");
System.out.println("CONNECTION SUCCESSFUL");
} catch (SQLException e) {
System.out.println("ERROR: Connection Failed!");
}
return connection;
}
public static void login(String username, String password, String login) throws ClassNotFoundException {
try {
System.out.println("INSERTING");
try (Statement stmt = getConnection().createStatement()) {
String sql = "INSERT INTO login (username, password) VALUES ('" + username + "', '" + password + "', '" + login + "');";
stmt.execute(sql);
}
getConnection().close();
System.out.println("INSERT SUCCESSFUL");
} catch (SQLException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static ResultSet getLoginDetails(String query) throws SQLException, ClassNotFoundException {
ResultSet rs;
try (PreparedStatement ps = getConnection().prepareStatement(query)) {
rs = ps.executeQuery();
ps.close();
getConnection().close();
}
return rs;
}
public static ResultSet getExistentDetails(String query) throws SQLException, ClassNotFoundException {
ResultSet rs;
try (PreparedStatement ps = getConnection().prepareStatement(query)) {
rs = ps.executeQuery();
getConnection().close();
}
return rs;
}
}
private void loginBtnMouseClicked(java.awt.event.MouseEvent evt) {
if (username.getText().isEmpty() || password.getText().isEmpty()) {
infoLabel.setVisible(true);
username.setText("");
password.setText("");
} else {
try {
databaseConnection.getLoginDetails("SELECT * FROM register WHERE email = '?' AND password = '?'");
String ts = new SimpleDateFormat("dd.MM.yyyy - HH.mm.ss").format(System.currentTimeMillis());
databaseConnection.login(username.getText(), password.getText(), ts);
JOptionPane.showMessageDialog(null, "Login succesful!");
new login().setVisible(true);
infoLabel.setVisible(true);
username.setText("");
password.setText("");
} catch (HeadlessException ex) {
JOptionPane.showMessageDialog(null, "Failed!");
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Output
I believe you have forgotten an important thing: properly preparing your PreparedStatement and opening/closing connections correctly.
Would you try the following rewritten getLoginDetails() method and take inspiration from it for the other methods?
public static ResultSet getLoginDetails(String query, String email, String password) throws SQLException, ClassNotFoundException {
ResultSet rs;
try (Connection conn = getConnection()) {
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1,email);
ps.SetString(2,password);
rs = ps.executeQuery();
// Do something with the ResultSet here or do not close the statement!
}
}
return rs; // should be something else! (as it could be already closed)
}
Then you certainly need to do something with the ResultSet! For example: check that the email/password combination exists in order to validate the login request.
Also, some important remarks and tips:
better check that the connection is valid after initialization using isValid(timeout)
think about a connection pool or at least some ways to reuse your connection(s)
eventually use existing tools (libraries like Apache) for your ORM (Object-Relation Mapping) and DAO (Database Access Object) layers. Actually, that's highly recommended.
closing a PreparedStatement will automatically close the associated ResultSet. Your code does not take that into account. Cf. https://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html
Keep me posted!
I'm trying to connect to my DB using JDBC. I wanted to make a method for connection and another method for selecting data. I am getting a red line in Eclipse on the 'Connection con = connectDB();' part. ( See also attached) Cany anyone give me advice?
public class DBJdbc {
//Statement stmt = null;
// connecting to DB
public void connectDB() {
//Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
// a method for selecting DB
public static void select() {
//connectDB();
String sql = "SELECT * from SAC_SUR";
try(Connection con = connectDB(); // I'm getting a red line here)
PreparedStatement pstmt = con.prepareStatement(sql)){
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
System.out.println("Id = " + id + "name = " + name);
} //while
} catch(SQLException e) {
System.out.println(e.getMessage());
}
}
red line here!!!
connectDB() method is of void type and not returning anything but when you are calling the method, you are assigning it to variable con. So you need to change the return type of connectDb to the Connection type.
public Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
You are trying to call non-static method into the static area, which is not allowed in Java. So I made this method static and returning the database connection.
Please update the below method into your code. It will resolve your problem.
public static Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "", "");
} catch(SQLException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
I am trying to connect a Neteans Java project with Mysql database and i cannot establish a connection and i do not know what could possibly go wrong
My Java code:
private void setupLoginEventListener() {
loginBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
rightFirstText = userName.getText();
rightText = password.getPassword();
if (rightFirstText.isEmpty() && rightText.length == 0) {
JOptionPane.showMessageDialog(JavaApplication6.this, "All fields are required", "Error", JOptionPane.ERROR_MESSAGE);
} else if (rightText.length == 0) {
JOptionPane.showMessageDialog(JavaApplication6.this, "Password is required", "Error", JOptionPane.ERROR_MESSAGE);
} else {
try {
conn = getDBConnection();
pst = conn.prepareStatement("select * from pdie where username =? and password=?");
pst.setString(1, rightFirstText);
pst.setString(2, new String(rightText));
rs = pst.executeQuery();
while (rs.next()) {
JOptionPane.showMessageDialog(JavaApplication6.this, "Login Successfull");
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(JavaApplication6.this, "Login Failed");
}
}
}
});
}
public Connection getDBConnection() {
Connection con = null;
String url = "jdbc:mysql://localhost:3536/";
String dbName = "projectdb";
String driver = "com.mysql.jdbc.Driver";
String connectUserName = "root";
String connectPassword = "";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + dbName, connectUserName, connectPassword);
System.out.println("CONNECTION ESTABLISHED.");
} catch (ClassNotFoundException | SQLException e) {
System.out.println("CONNECTION COULD NOT BE ESTABLISHED.");
}
return con;
}
any ideas?
it gives me an error for null pointer exception in this line
pst = conn.prepareStatement("select * from pdie where username =? and password=?");
type these lines
st=con.createStatement();
String sql="SELECT * FROM TAB";
rs=st.executeQuery(sql);
and try to print a a field; to test quickly if the problem is in you prepared statement but probably it's in your conn object.
I am using Java and MySQL.
I have two sql statement in two separate function, one create database, another create tables.
I try to write try & catch exception block in each function, it works, like code below.
public class j_sql1 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost";
static final String DB_URL2 = "jdbc:mysql://localhost/zxc";
static final String USER = "root";
static final String PASS = "";
static Connection conn = null;
static Statement stmt = null;
public static void create_db()
{
conn = null;
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE DATABASE zxc";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2){}
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
}
}
public static void create_tables ()
{
conn = null;
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL2, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE TABLE ABC("+
"abc_ID int NOT NULL AUTO_INCREMENT,"+
"abc_Name varchar(50),"+
"PRIMARY KEY (abc_ID))";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2)
{}
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
}
}
public static void main(String[] args)
{
create_db();
create_tables();
}
}
But what if only one catch exception block in the main for my two try blocks in the two functions something like the code below, possible?
public class j_sql1 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost";
static final String DB_URL2 = "jdbc:mysql://localhost/zxc";
static final String USER = "root";
static final String PASS = "";
static Connection conn = null;
static Statement stmt = null;
public static void create_db()
{
conn = null;
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE DATABASE zxc";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
}
public static void create_tables ()
{
conn = null;
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL2, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE TABLE ABC("+
"abc_ID int NOT NULL AUTO_INCREMENT,"+
"abc_Name varchar(50),"+
"PRIMARY KEY (abc_ID))";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
}
public static void main(String[] args)
{
try
{
create_db();
create_tables();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2)
{}
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
}
}
}
And why the variable like Connection, Statement and the functions have to be declared to static?
Thank You.
In the static main, there is no object instance of the class j_sql1. Hence only static fields may be read.
You should do
Naming convention the same as 99.9 % of java users:
class JSql1
void createDB()
void createTables()
Instantiate an object, and call functions on it:
... main(...) {
JSql1 app = new JSql1();
try {
app.openConnection();
app.createDB();
app.createTables():
} catch (SQLException e) {
Logger.getLogger(JSql1.class.getName()).log(Level.FATAL, "...", e);
} finally {
app.close();
}
When createDB fails, there is no need to continue, hence createDB should throw the
exception.
Also the functions are uaseful inside a single connection, so create the connection
separately.
Design decision, but at least for statements declare all as locally as possible
Especially try-with-resource for automatically closing helps here
class JSql1;
Connection conn;
void createTables() throws SQLException {
try (Statement stmt = conn.createStatement()) {
String sql = "CREATE TABLE ABC(" +
"abc_ID int NOT NULL AUTO_INCREMENT," +
"abc_Name varchar(50)," +
"PRIMARY KEY (abc_ID))";
stmt.executeUpdate(sql);
}
}
i am using xampp mysql, this code is for JDBC program. actually there are two class one is dbconnect.java and another is login.java. I want to access the connection object (i.e. conn) in another class(i.e. login.java). But i don't have proper idea, i have included the code here please suggest me what is the problem and what are the solutions?
This is the code of dbconnect.java
package stundentrecord;
import java.sql.Connection;
import java.sql.DriverManager;
public class dbconnect {
public void conect(){
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "studentRecord";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try{
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
if(con==null){
System.out.println("Connection cannot be established");
}
// con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
and here is the code from another class named login.java
if(source==login){
if(username!=null && password!=null) {
Connection conn= null;
Statement stmt = null;
dbconnect db = new dbconnect();
db.conect();
String query = "SELECT * from userlogin";
try{
stmt=(Statement) conn.createStatement(); // here is the problem
ResultSet rs = stmt.executeQuery(query); // here is the problem
while (rs.next()) {
String user = rs.getString("username");
String pass=rs.getString("password");
System.out.println("Welcome "+user);
}
} catch(SQLException ex){
ex.getMessage();
}
StundentRecord SR = new StundentRecord();
} else {
JOptionPane.showMessageDialog(null,"Username or password field is empty","error !!",JOptionPane.ERROR_MESSAGE);
}
}
What is the real problem and how to solve it?
The easiest way would be to make the connect method non void and return the connection:
public Connection conect() {
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "studentRecord";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
if (con == null) {
System.out.println("Connection cannot be established");
}
return con;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
You should return your CONNECTION object from you connection class and assign it to your login class... Now your connection object is null...