I am learning Java getting trouble in JDBC connection.
Following is my code:
public class DemoPro {
public void test() {
Connection con;
Statement stmt;
ResultSet rs;
System.out.println("Looking for connection");
try{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String dburl="jdbc:ucanaccess://E://WEB Project//SCMPayBoard//Database/SCMEmpPayment.accdb";
con=DriverManager.getConnection(dburl,"","");
System.out.println("Connection successfully");
stmt=con.createStatement();
String verify = "Select * from TestTable";
stmt.executeQuery(verify);
rs = stmt.getResultSet();
System.out.println("Executing Query");
while(rs.next())
{
System.out.println("Result/n/n/n");
System.out.println(rs.getString(2) + " : " + rs.getString(3));
}
System.out.println("Closing Connection");
con.close();
}catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(DemoPro.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
DemoPro dp=new DemoPro();
dp.test();
}
}
Output :
Looking for connection
Connection successfully
Executing Query
Closing Connection
BUILD SUCCESSFUL (total time: 1 second)
All sysout is executing but Table data is not fetched
How do i know Table is getting access or not
What should i do getting no result as expected
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 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 am getting an SQL error while establishing database connection in Java (Jdbc:Odbc). How do I fix this error?
Here is the relevant code:
import java.sql.*;
import java.lang.*;
import java.io.*;
public class db {
public static void main(String args[]) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:data","system","password");
System.out.println("\n connection established");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from stud");
System.out.println("details of empdata\n");
while(rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
} catch(Exception e) {
System.out.println("sql error");
}
}
}
/* Execute query requires string as argument and u have not use semi colon at query if u are getting class not found exception than handle it first
THIS SHOULD BE PASS IN DOUBLE QOUTES="select * from stud;"*/
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:data","system","password");
System.out.println("\n connection established");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from stud;");//----HERE--*/
System.out.println("details of empdata\n");
while(rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
} catch(Exception e) {
System.out.println("sql error");
}
}
}
I have been trying this for a few hours now but with no success. I downloaded the JDBC driver and it shows that it is one of my referenced libraries under my Package Explorer in Eclipse but every time I try to run my code I get errors. My database is fine as I can change it and view it from the MySQL Command Line Client.
I actually followed a guides directions on how to do it, only replacing the information from their database to information about mine.
import java.sql.*;
public class FirstExample {
//JDBC Driver Name and Database URL
final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final static String DB_URL = "jdbc:mysql://localhost/test_database";
//Database Credentials
static final String USER = "user_one";
static final String PASS = "User_one_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//Register JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
//Open a Connection
System.out.println("Connecting to the Database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//Execute a Query
System.out.println("Creating Statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM user";
ResultSet rs = stmt.executeQuery(sql);
//Extract Data from Result Set
while (rs.next()) {
//Retrieve by Column Name
int id = rs.getInt("id");
String first = rs.getString("name");
//Display Values
System.out.print("ID: " + id);
System.out.println("Name: " + first);
}
//Clean Up Environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
//Handle Errors For JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle Errors for Class.forName
e.printStackTrace();
} finally {
//Finally Block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
//Nothing We Can Do
}
try {
if (conn != null)
conn.close();
} catch (Exception se) {
se.printStackTrace();
}//End Finally Try
}//End Try
System.out.println("Goodbye!");
}//End Main
}//End First Example
Here is the error I get http://pastebin.com/hLSxV3aq
I'm trying to teach myself how to connect to a msaccess database in java.
I have set up a class to access the database as follows
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public abstract class AccessDBConnect2 {
public static Connection connect(){
String fileName = "C:/Users/Bridget/Documents/EmployeeSys.accdb";
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
con = DriverManager.getConnection(url,"","");
} catch (Exception e) {
// Handle exceptions ...
System.out.println(e.toString());
System.out.println("A problem accessing the database");
e.printStackTrace();
} finally {
try { if(con!=null) {con.close();} } catch (Exception e) {}
}
return con;
}
public static void closeConnection(Connection conn){
try{
conn.close();
}catch (Exception e){
}
}
Then I have my code which is just trying to select everything from the table.
I have created the table in msAccess and the code seems to get through the connect method in the above code without any problems, indicating it is finding the database and accessing it somewhat. The problem happens when I call the prepareStatement using the connection, i.e. code line:
stm = conn.prepareStatement(sql);
The full code is:
import java.sql.*;
public class Program2{
public static void main(String[] args) {
try{
// Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// Establishing db connection
Connection conn = AccessDBConnect.connect();
// Displaying all records from employee file
System.out.println("Display records of all employees");
display(conn);
// Closing the connection
AccessDBConnect.closeConnection(conn);
}catch (Exception e){
System.out.println("Error");
}
}
// Display details of all employees
public static void display(Connection conn){
PreparedStatement stm = null;
// SQL statement
String sql = "SELECT * FROM Employee";
ResultSet rs;
try {
stm = conn.prepareStatement(sql); // Prepare the SQL statement
rs = stm.executeQuery(); // Execture the SQL statement
// Navigate through the ResultSet and print
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String address = rs.getString("address");
System.out.println("ID: \t \t" + id);
System.out.println("Name: \t \t" + name);
System.out.println("Gender: \t" + gender);
System.out.println("Address: \t" + address);
System.out.println(" ");
}
// Closing the resultSet
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void test(){
int a = "hello";
}
}
You are receiving the error because when you try to call .prepareStatement the connection is closed. Your AccessDBConnect2 class contains a finally block that closes the connection before it returns. Fix that class so it leaves the connection open.
By the way, the JDBC-ODBC Bridge has been removed from Java 8 and is effectively obsolete. You might be interested in this alternative:
Manipulating an Access database from Java without ODBC
I've removed the obviously incorrect answer :) another possibility:
I would think the issue is in your connection to the database, try changing 'C:/Users/Bridget/Documents/EmployeeSys.accdb' to 'C:\\Users\Bridget\Documents\EmployeeSys.accdb'