Error Loger and verification authentification java - java

I am trying to get my code to check if my username and password are in the database only I have errors everywhere. Do you have a solution?
here my code in my Login_form :
PreparedStatement st;
ResultSet rs;
// donnez l'username et le password
String username = jTextField_Username.getText();
String password = String.valueOf(jPasswordField.getPassword());
// requete indiquant si les identifiants existent
String query = "SELECT * FROM 'users' WHERE 'username' = ? AND 'password' = ?";
try {
st = Connecter.getConnection().prepareStatement(query)
st.setString(1, username);
st.setString(2, password);
rs = st.executeQuery();
if(rs.next())
{
// Show my new form
}else{
// Error message
}
} catch (SQLExeption ex) {
Logger.getLogger(Login_Form.class.getName()).log(Level.SEVERE, null, ex);
}
and this is my code of my connector
package javaapplicationhotel2;
import java.sql.*;
public class Connecter {
static Object getConnection() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
Connection con;
public Connecter() {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
}catch(ClassNotFoundException e){
System.err.println(e);
}
try{
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel","root","");
}catch(SQLException e){System.err.println(e);}
}
Connection obtenirconnexion(){return con;}
PreparedStatement prepareStatement(String select__from_classe) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}

The Problem seems to reside in your Connecter class. Especially in the getConnection() and prepareStatement() methods since they always return throwing an UnsupportedException. Another issue is that getConnection() is of the return type Object, even though you treat it as a Connector in your try block. Therefore I'd suggest you changing getConnection's return type to Connection and returning a new Connection() or using new Connection() in the first place. Also you may want to replace your setString(int, String) calls, which presumably replace the '?' with the corresponding username and password, with String.format(String, Object...). You can use this method to replace certain parts of a String (eg. %s for Strings, %d for Integer, etc.) So in your case you would use it as the following:
String format = "SELECT * FROM 'users' WHERE 'username' = %s AND 'password' = %s;"
String query = String.format(format, username, password);
As a side note:
In modern jdbc you are actually not required to load the Driver class with Class.forName(String), so you may omit it.
One last thing:
It'd be nice if you could indent your code appropriately the next time, since that would make understanding it a lot easier.

Related

How to tell when there is a connection database issue?

I need to make a special treatment when a connection problem to the database is occurring like database server down and not an sql problem.
In the source code we can get various exceptions but which ones are belonging to the connection ones ?
We would like if this kind of problem occurs to make less logs.
EDITED
I have many methods that perform connection to the database but all get the session from the same method (initSession):
Here an example:
private Session initSession(HibernateUtil hibernateUtil) {
Session oSession = null;
try {
oSession = hibernateUtil.getSession();
} catch (Exception e) {
log.error("unable to log, Please check the details of your database");
}
return oSession;
}
public List findAlerts(int pFirstLine, int pNbElement) throws AnalyzerException {
List oAlerts = new ArrayList();
Session oSession = initSession(lHibernateUtil);
try {
oAlerts = AlertFinders.instance().findAlertByStatus(oSession, false, pFirstLine, pNbElement);
Iterator iterAlerts = oAlerts.iterator();
while (iterAlerts.hasNext()) {
...
}
} catch (UnableToLocateObjectException eU) {
throw new AnalyzerException(eU.getMessageSource(), eU.getClassNameSource(), eU.getMethodSource(), eU);
} finally {
oSession.close();
}
return oAlerts;
}
Multiple possible ways.
Use Java Connection isValid method.
Use connection pool - All major connection
pools support this functionality (including c3p0 and dbcp).They can
throw SQLException has getErrorCode() and getSQLState() methods
Write Java code & poll frequently - sample code below
Run arguments sample: jdbc:oracle:thin:#localhost:1521:XE system mypassword123 oracle.jdbc.driver.OracleDriver
public class DbConnCheck {
public static void main(String[] args) throws Exception {
String url = args[0];
String username = args[1];
String password = args[2];
String driver = args[3];
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
try {
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("SELECT SYSDATE FROM DUAL");
while(rs.next()) {
System.out.println(rs.getObject(1));
}
} finally {
conn.close();
}
}
}
Edit : Adding details on hibernate part
Not done in Hibernate but to be precise you can check in connection pool configuration.
If using c3p0 then check how you can best use setting like idle_test_period, preferredTestQuery and testConnectionOnCheckout;
If using dbcp then validationQuery can do the job.
If you want to use c3p0 with Hibernate and Spring check this link

Java - Populate a JCombobox with SQLite database

I want to populate a JComboBox with a database column (SQLite).
My database connection is setup through a class called DatabaseConnection setup in anther package.
Here is how it looks like
import java.sql.*;
import javax.swing.JOptionPane;
public class DatabaseConnection {
Connection conn = null;
public static Connection ConnectDB() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:database.db");
JOptionPane.showMessageDialog(null, "Connection Established");
conn.setAutoCommit(false);
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
In my JFrame class I am creating following method, which according to a youtube tutorial should work
public void PopulateJCB()
{
String queryString = "SELECT DISTINCT [Account Name] FROM main ORDER BY [Account Name]";
try
{
Connection statJCBaccountname = DatabaseConnection.ConnectDB();
Statement stmt = statJCBaccountname.createStatement();
ResultSet rsJCBaccountname = stmt.executeQuery(queryString);
while (rsJCBaccountname.next())
{
comboAccountName.addItem(rsJCBaccountname.getString(1));
}
catch (SQLException e)
{
e.printStackTrace();
}
}
But it displays following errors at "comboAccountName.addItem(rsJCBaccountname.getString(1));"
Multiple markers at this line
- Type safety: The method addItem(Object) belongs to the raw type JComboBox. References to generic type JComboBox<E> should be
parameterized
- comboAccountName cannot be resolved
Please help!
I'm not really sure what you're expecting...
statJCBaccountname isn't even in the code example you've provided, but the compiler is saying that the variable is undefined
There is no such method as createStatement in the DatabaseConnection class
You need to resolve these issues before the program will compile. I'd suggest staying away from YouTube tutorials unless you know the author.
Take a look at JDBC Database Access for more details...

Using database mysql in Java

I have started trying out some stuff so that I can use mysql database together with Java. First of all I have some questions about it.
I have used mysql a lot with PHP development but never with Java. Can I use the MySQL that MAMP brings or do I have to install it stand alone or something?
and second.. I have created this code with the help of a tutorial but the only output I get is
com.mysql.jdbc.Driver
The code that I have used for this you can find below:
package Databases;
import java.sql.*;
public class MysqlConnect{
/* These variable values are used to setup
the Connection object */
static final String URL = "jdbc:mysql://localhost:3306/test";
static final String USER = "root";
static final String PASSWORD = "root";
static final String DRIVER = "com.mysql.jdbc.Driver";
public Connection getConnection() throws SQLException {
Connection con = null;
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, USER, PASSWORD);
}
catch(ClassNotFoundException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
return con;
}
public void getEmployees() {
ResultSet rs = null;
try {
Statement s = getConnection().createStatement();
rs = s.executeQuery("SELECT id, name, job_id, location FROM person");
System.out.format("%3s %-15s %-7s %-7s%n",
"ID", "NAME", "JOB ID",
"LOCATION");
System.out.format("%3s %15s %7s %7s%n",
"---", "---------------",
"-------", "--------");
while(rs.next()) {
long id = rs.getLong("id");
String name = rs.getString("name");
long job = rs.getLong("job_id");
String location = rs.getString("location");
System.out.format("%-3d %-15s %7d %5s%n",
id, name, job, location);
}
}
catch(SQLException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
}
}
It's coming from the following block:
catch(ClassNotFoundException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
That's a pretty poor way of handling exceptions. You're just printing the exception message. You have no clue what's going on. Rather just throw it (which will end up with a nice stacktrace), or print a more descriptive message along alone the exception message, e.g.
catch(ClassNotFoundException e) {
System.out.println("JDBC driver class not found in runtime classpath: " + e.getMessage());
System.exit(-1);
}
How to fix the particular exception is in turn actually a second question (with a pretty obvious answer: just put JAR file containing JDBC driver class in runtime classpath), but ala, you may find this mini-tutorial helpful then: Connect Java to a MySQL database.
Unrelated to the concrete problem, I'm not sure which tutorial you're reading there, but I'd take it with a grain of salt. Apart from poor exception handling, it's also leaking DB resources in getEmployees() method by never closing the result set, statement and connection. This is absolutely not a good practice either. How to do it is also already covered in the aforelinked mini-tutorial. See further also: How often should Connection, Statement and ResultSet be closed in JDBC?
Yes, you need to install MySQL server locally or remotely.
The code will be usable if you also downloaded jdbc Driver jar from MySQL download pages. and you configured your MySQL instance with the proper username and password.

Am I closing this Oracle pooled connection correctly?

I am attempting to use a pooled connection for my web application in Java. I am using an Oracle database and here is my code:
public class DatabaseHandler
{
static private Connection m_database = null;
static private OracleConnectionPoolDataSource pooledSource = null;
/**
* Attempts to open an Oracle database located at the specified serverName and port.
* #param serverName Address of the server.
* #param portNumber Port to connect to.
* #param sid SID of the server.
* #param userName Username to login with.
* #param password Password to login with.
* #throws WebApplicationException with response code 500 Internal Server Error.
*/
static public void openDatabase(String userName, String password,String serverName,int portNumber, String sid)
throws WebApplicationException
{
try
{
// Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
// Create a connection to the database
String url = "jdbc:oracle:thin:#" + serverName + ":" + portNumber + ":" + sid;
pooledSource = new OracleConnectionPoolDataSource();
pooledSource.setUser(userName);
pooledSource.setURL(url);
pooledSource.setPassword(password);
m_database = pooledSource.getConnection();
}
catch (ClassNotFoundException e)
{
// Could not find the database driver
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
catch (SQLException e)
{
// Could not connect to the database
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
/**
* Attempts to execute the specified SQL query.
* #throws WebApplicationException with a response code of Bad Request
* if the query is invalid SQL.
*/
static public ResultSet makeQuery(String query) throws WebApplicationException
{
ResultSet rs = null;
if (m_database != null)
{
try
{
Statement stmt = m_database.createStatement();
rs = stmt.executeQuery(query);
}
catch (SQLException e)
{
// invalid query
System.out.println(query);
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
return rs;
}
/**
* Attempts to close the database.
* #throws WebApplicationException with a response code of 500 Server error
*/
static public void closeDatbase() throws WebApplicationException
{
try
{
m_database.close();
pooledSource.close();
}
catch(SQLException e)
{
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
}
I am doing this in Eclipse and I have a warning that pooledSource.close() is deprecated. I have never used a pooled connection before and I just want to be sure that I am doing everything correctly. Is there a better way to close an Oracle pooled resource?
A deprecated method means that this method shouldn't be used. In future releases, the close() method can be purged entirely. I suggest removing pooledSource.close().
Also, I would suggest not to have a static instance of a Connection and DataSource as you require a connection on request and not keep it alive throughout the application. Always close a ResultSet first and then a Connection and guarantee the closure by adding them in a finally block.
The connection must be closed to be returned to the pool.
Always close your connection in a finally-block.
Never hold connection references as a class member - this is error prone and bad design. Connections should be aquired as late as possible and released as soon as possible. It does not make sense to hold something like that as class member.
Close connections where they are used. Your code is error prone again here. If you forget to call closeDatabase() you're leaking connections.
Attention:
Do not jumble closing the connection and closing the connection pool here.
Because it was requested here's some code for correct and good connection handling:
public void doSomethingWithDb(Connection con, ...) {
boolean release = (con == null);
try {
con = PersistenceUtils.getConnection(con); //static helper return a new conenction from pool when provided con==null otherwise simply returns the given con
//do something
if(release) {
con.commit();
}
}
catch(SQLException e) {
//handle errors, i.e. calling con.rollback() but be sure to check for con!=null before. Again maybe null-safe static helper method here.
}
finally {
if(release && con!=null){
con.close();
}
}
}
I am using Connection as method parameter in order to be able to call many of such methods in one db transaction. But you can always put null as first argument for Connection and the method get a connection from pool for you.
When you call another "DB-Method" inside a "DB-Method" you just provide your connection to the underlying method - so you have everything in one transaction then.
As you see correct JDBC code produces much boilerplate code. In the first step you can reduce it by implementing a Utility-Class like PersistenceUtils which provides static null-safe methods like commit(Connection), rollback(Connection), getConnection(Connection), close(Connection) ...
With that you get rid of all null-checks and you can include logging or something else there, too.

what is the step do i need to call database

i am new in developing android application. Now, i have a database file which is "database.accdb" in assets folder.
what should i do inside the java code in order to access the database
UPDATE I just realized that you're writing an Android application. ODBC or Microsoft Access database will NOT work in Android. SQLite is used in Android, you have to subclass SQLiteOpenHelper, and override onCreate(), and onUpgrade(). Below is the direction of how to access Microsoft Access database on a regular Java program.
Looks like you're trying to access a Microsoft Access database. In this case, you need to instantiate the JDBC-ODBC driver by
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String connectionUri = "jdbc:odbc:" + /*PATH TO YOUR FILENAME*/;
connection = DriverManager.getConnection(connectionUri, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Then you can use your connection like you use any other JDBC database connection. For example, you can do:
Connection connection = .... /* Get my connection */;
try {
PreparedStatement ps = connection.prepareStatement(
"SELECT id, password FROM users WHERE email LIKE ?");
ps.setString(1, email);
ResultSet result = ps.executeQuery();
while (result.next()) {
/* do whatever you want with the result */
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
/* Close the connection */
}

Categories

Resources