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...
Related
I was working on a java project and it was working just fine. I was able to make connections. I closed all the connections properly in finally block. Now I am not able to make connections or even open psql in my terminal. How can I make it work as before. Much much appreciated
import java.sql.Connection;
import com.mchange.v2.c3p0.*;
public class MyConnection {
public static Connection getConnection(){
ComboPooledDataSource cpds1 = new ComboPooledDataSource();
String dbDriver = "org.postgresql.Driver";
String dbName = "jdbc:postgresql://localhost/postgres";
cpds1.setJdbcUrl(dbName);
String userName = "user_1";
cpds1.setUser(userName);
String password = "mypass";
cpds1.setPassword(password);
cpds1.setMaxStatements( 180 );
try
{
cpds1.setDriverClass(dbDriver);
return cpds1.getConnection();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
This is where I'm calling it
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
PrintWriter writer = response.getWriter();
JSONObject jo = new JSONObject();
JSONObject jObj;
Statement stmt = null;
Connection con = null;
PreparedStatement ps;
ResultSet rs = null;
try
{
jObj = UtilityClass.getJSON(request);
String uname = ((String) jObj.get("uname"));
String pass = ((String) jObj.get("pass"));
String sql = "SELECT * FROM users WHERE username = ?";
try
{
con = MyConnection.getConnection();
System.out.println("Got Connection");
stmt = con.createStatement();
ps = con.prepareStatement(sql);
ps.setString(1, uname);
rs = ps.executeQuery();
if(rs.next())
{
if(BCrypt.checkpw(pass,rs.getString("password")))
{
HttpSession session = request.getSession();
session.setAttribute("uname", uname);
if(session.isNew())
{
System.out.println("new");
}
if(uname.equals("admin"))
{
session.setAttribute("role", "admin");
jo.put("status", "admin");
}
else
{
session.setAttribute("role", "user");
jo.put("status", "authenticate");
}
}
}
writer.print(jo);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Not Connected");
}
finally
{
if(rs != null)
{
rs.close();
}
if(stmt != null)
{
stmt.close();
}
if(con != null)
{
con.close();
}
}
}
catch(Exception e)
{
System.out.print("JSON Exception");
}
}
Usually, DB Admins are using pooling technologies on Databases. For PostgreSQL one of the more popularly is a PGBOUNCER. We used PGBOUNCER in our large project, the result is excellent. I recommend it to you. To get more information about the pooling system you can read this link. For About Pooling
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 getting error when I try to connect database
Error:com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to
Ptakip.Connection
Ptakip is my Package
Connection is my Class
Here is the Connection Class Code ;
import java.sql.*;
public class Connection {
private Connection cn;
public Connection connector( )
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:sqlserver://localhost\\MyServer:
1433;databaseName=TEST;user=Glassfish;password=pass;");
System.out.println("connected");
}
catch(Exception ex) {
System.out.println("Error:" + ex.getMessage());
System.out.println(cn);
}
return cn;
}
}
your class has the same name as the class in the package java.sql that's why u have this conflict ,juste try to change the name to Connexion ,it should work
Try to make a connection like this. it may help you
String url = "jdbc:mysql://localhost:3306/";
String dbName = "demo”
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "mypasswd";
try {
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,userName,password);
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to write a java program connecting to a MySQL database. But I am getting this error:
No suitable driver found for jdbc:mysql//localhost:3306/test
I have already installed mysql-connector-java.5.1.23-bin.jar. I am still getting this error.
Here is my program:
package database_practice;
import java.sql.*;
public class CreateConnection {
private Connection conn = null;
public static void main(String args[]) {
CreateConnection conn = new CreateConnection();
conn.getConnection();
}
public Connection getConnection() {
try {
String url = "jdbc:mysql//localhost:3306/test";
String username = "root";
String password = "admin1234";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);
System.out.println("Database Created...!!!");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error occured while connecting to database");
}
return conn;
}
}
Your connection string is wrong. This:
"jdbc:mysql//localhost:3306/test"
should be:
"jdbc:mysql://localhost:3306/test"
Note the colon after "mysql".
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);