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.
Related
I am trying connection with database but this error frustrates me . Can anyone help me out what is the problem here?
I want to connect to SQL Server from Eclipse.
public class JDBC_Test {
public static void SQLServerConnection() {
try {
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=Northwind";
String user = "sa";
String password = "832Waseem#";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(url, user, password);
System.out.println("Connection Created Successfully.......");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from categories");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
}
con.close();
System.out.println("Connection Closed Successfully.......");
} catch (Exception e) {
// System.out.println("Unable to create Connection reason is as below.......");
e.printStackTrace();
}
}
public static void main(String args[]) {
SQLServerConnection();
}
}
My Error:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'sa'. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)
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 have a Problem in Java MySQL login screen. i connect my MySQL successfully.
but when i put my login and password it throws a nullpointerExpception error.
here i am going to add MySQL java code and Jframe code for login
Connection conn=null;
public static Connection dbconnector()
{
try{
Class.forName("org.sqlite.JDBC");
Connection conn=DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Jani_na\\Desktop\\login.sqlite");
JOptionPane.showMessageDialog(null,"succesful");
return null;
}
catch(Exception e)
{JOptionPane.showMessageDialog(null, e);
return null;
}
here the login Jframe code
Connection connection=null;
/**
* Create the application.
*/
public login() {
initialize();
connection=JDBC.dbconnector();
}
btnMessage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String Query="SELECT username,password "
+ "FROM login "
+ "WHERE text username = ? "
+ "AND text password = ?";
PreparedStatement pst=connection.prepareStatement(Query);
pst.setString(1,textField.getText() );
pst.setString(2,passwordField.getText() );
ResultSet rs = pst.executeQuery();
int count=0;
while(rs.next())
{
count=+1;
}
if(count ==1)
{
JOptionPane.showMessageDialog(null,"Correct");
}
else if (count>1)
{
JOptionPane.showMessageDialog(null,"duplicate");
}
else
{
JOptionPane.showMessageDialog(null,"Wrong password or username!!\n try again !! ");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
Change return null to return connection.
Connection conn=null;
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Jani_na\\Desktop\\login.sqlite");
JOptionPane.showMessageDialog(null,"succesful");
return conn;
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
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...
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);