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 */
}
Related
I am working on a hotel management system project and I want to make a login platform, which takes data from an AWS RDS PostgreSQL server that I have created. The problem is that people from other networks who I sent the .exe file of this project can't login but I can.
I have created the tables I wanted in pgAdmin4 and also I have installed the Postgres drivers in my project libraries.
Here is my connection class, where URL, user and pass are defined in the project:
public class ServerConnection {
static Connection getConnection() {
Connection connection = null;
try{
connection = DriverManager.getConnection(url, user, pass);
if(connection != null) {
System.out.println("Connected");
}
else {
System.out.println("Failed");
}
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
And below is the login method:
public void performLogin() {
PreparedStatement st;
ResultSet rs;
String user = username.getText();
String pass = String.valueOf(password.getPassword());
String query = "SELECT * FROM ADMINS WHERE username=? AND passw=?";
try {
st = serverConnection.getConnection().prepareStatement(query);
st.setString(1, user);
st.setString(2, pass);
rs = st.executeQuery();
if(rs.next()) {
hotelFrame2 hf2 = new hotelFrame2();
this.dispose();
}
else {
JOptionPane.showMessageDialog(null, "Invalid Username / Password","LoginError",2);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
How can I fix it?
The problem is that people from other networks who I sent the .exe
file of this project can't login but I can.
It seems you are authorizing only your computer(IP) to connect to the RDS database, to solve your issue you have to open the flow to the other people by changing the security group.
By the way, using JDBC with AWS really hurt me, it is really an old way, it's better to look at JPA, Hibernate, or even some other AWS services.
I'm trying to write a servlet application for learning purposes that connects to an Oracle database, queries some data and then prints it to the browser. Simple!
However, I'm experiencing an ORA-01017: invalid username/password when attempting to connect to a locally installed and running version of Oracle XE (19c). For the sake of testing the connection, I'm connection with the system user. Here's my code:
// http://localhost:8080/demo/
public class DemoServ extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1523:xe", "system", "SYSTEM");
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The user that I'm using absolutely does exist, and I can connect using SQL Developer without issue.
I would be willing to put this down to my own ignorance of Java, but if I run the following code independently of any servlet, I can connect and execute the sample query!
public class DataReader {
public static void main (String [] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1523:xe", "system", "SYSTEM");
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery("SELECT count(*) num FROM dual");
if (rs.next()) {
int i = rs.getInt("num"); // get first column returned
System.out.println("number: " + i);
}
rs.close();
statement.close();
con.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
I've been searching Google for solutions to this, but I have been unable to find a solution, so here I am.
I'm working on Windows 10, using Java 1.8 and Oracle 19c XE.
Any help would be great. Thanks
Okay, I finally go this to work, but I cannot explain why.
Oracle 19c is case sensitive, which I knew. I attempted to disable this, but as it's a depreciated feature, this seemed expeditious. I altered the password for the system user to be "system", and I can connect successfully. "SYSTEM" as a password continues to fail.
What strikes me as odd about this is that I'm sure that I tried to use the "system" (lowercase) password in the past. :(
Anyway, I probably was doing something daft, but at least I'm got over the hump. Phew!
Thank you to everyone!!
I am trying to create a table on in-memory sqlite database. I have a method called createTable to create a table which initializes a connection to the database with getConnection method.
createTable:
private void createTable() {
try {
final Connection connection = getConnection();
final Statement statement = connection.createStatement();
statement.execute(
"CREATE TABLE videos (id INTEGER PRIMARY KEY, title VARCHAR(255), description TEXT, path TEXT, category VARCHAR(255), published INTEGER DEFAULT 0, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP);");
statement.close();
connection.close();
} catch (final SQLException e) {
LOGGER.warn("Failed to create table.", e);
}
}
getConnection
private static Connection getConnection() {
try {
Class.forName("org.sqlite.JDBC");
return DriverManager.getConnection("jdbc:sqlite:");
} catch (final Exception e) {
LOGGER.warn("Failed to get connection.", e);
throw new RuntimeException(e);
}
}
To test the database I wrote a simple insert method:
public void insert() {
try {
final Connection connection = getConnection();
final Statement statement = connection.createStatement();
statement.executeUpdate(
"INSERT INTO videos (title, path, category) VALUES ('test title', 'test path', 'test category');");
statement.close();
connection.close();
} catch (final SQLException e) {
LOGGER.warn("Failed to insert.", e);
}
}
When I do
this.createTable();
this.insert();
I got the following error:
2017-09-17 22:38:02 WARN Database:128 - Failed to insert.
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: videos)
at org.sqlite.core.DB.newSQLException(DB.java:909)
at org.sqlite.core.DB.newSQLException(DB.java:921)
at org.sqlite.core.DB.throwex(DB.java:886)
at org.sqlite.core.NativeDB._exec_utf8(Native Method)
at org.sqlite.core.NativeDB._exec(NativeDB.java:87)
at org.sqlite.jdbc3.JDBC3Statement.executeUpdate(JDBC3Statement.java:116)...
For connections I am using org.xerial:sqlite-jdbc's v3.20.0.
Any ideas why table is not getting created? I am not seeing any exception or anything. SQLFiddle for the example above seems to be fine.
If I read the documentation correctly, the database only exists within its database connection by default:
Instead, a new database is created purely in memory. The database ceases to exist as soon as the database connection is closed. Every :memory: database is distinct from every other. So, opening two database connections each with the filename ":memory:" will create two independent in-memory databases.
The easiest fix would be to not open a second connection, but keep using the connection that you used to create the table for the other database queries as well.
If you want to open multiple connections, you can set the ?cache=shared parameter on the database url.
When a customer gets removed from the database, his status has to be set to offline (rather than actually deleting the customer from the database). In my database I'm using tinyint(1) to set the status to 0 (inactive) or 1 (active). Now how do I go about coding this?
// Delete a customer on the database by setting his status to inactive
public void deleteCust(int id) throws DBException {
// connect (and close connection)
try (Connection conn = ConnectionManager.getConnection();) {
// PreparedStatement
try (PreparedStatement stmt = conn.prepareStatement(
"update customer set active = ? where id = ?");) {
stmt.settinyint(1, 0);
stmt.setInt(2, id);
stmt.execute();
} catch (SQLException sqlEx) {
throw new DBException("SQL-exception in deleteCust - statement"+ sqlEx);
}
} catch (SQLException sqlEx) {
throw new DBException(
"SQL-exception in deleteCust - connection"+ sqlEx);
}
}
I'm using an SQL database via USB webserver on localhost. I'm unsure whether this works right now because the rest of my code is incomplete and I'm unable to test, but I have to be sure before continuing. Thank you
use setByte() instead.
because TINYINT in SQL is equal to byte in java, also it has some methods, like: setByte() and updateByte() and getByte()
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.