Is there a standard way to connect a Java program to a MySQL database, and which is the easiest one?
JDBC is the standard way also the easiest.
In addition to answer posted above, JPA (Hibernate) is even easier one once you cross the initial barrier called learning curve (and before you are hit by next one called, Performance Optimization). On the serious note, Yes JPA is also a standard way to connect and query pretty much any database the same way.
JDBC is the standard way. Below is the sample java code to connect MySQL database:
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String db = "testdb";
String dbUser = "root";
String dbPasswd = "mysql123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "DELETE FROM user WHERE email = 'riponalwasim#gmail.com'";
int delete = st.executeUpdate(sql);
if(delete >= 1){
System.out.println("Row is deleted.");
}
else{
System.out.println("Row is not deleted.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
Maybe object-relational mapping with Hibernate is a useful way for you.
Related
I am trying to figure out how to encrypt a sqlite database in non-android java.
It does not seem to be super straight forward, but I Willena jdbc crypt which does seem to be able to create an encrypted database, but I simply cannot figure out how to access a SQLCipher 4 encrypted database with it.
Here is my code.
String path = "jdbc:sqlite:C:\\Users\\User1\\Desktop\\testServer232.db";
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection(path+"?cipher=sqlcipher&key=a");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(3, 'leo1')");
statement.executeUpdate("insert into person values(4, 'yui1')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e.getMessage());
}
}
This code does work, but I don't think that it produces a SqlCipher 4 encrypted database. When I try to open it with DB browser for Sqlite, it does not allow me access when I put the password = a.
Where am I going wrong?
Ok, so I ended up finding the creator of the repository. And he solved it easily and answered really fast.
Here is the solution:
Here are a few things that could be tested:
Use version 3.31.1
Try to do the database connection using "jdbc:sqlite:file:C:\Users\User1\Desktop\test.db?cipher=sqlcipher&key=password123"as URI (notice the added "file:").
Try to add the legacy parameter for SQLCipher as available here (https://github.com/Willena/sqlite-jdbc-crypt#aes-256-bit-cbc---sha1sha256sha512-hmac-sqlcipher). The URI will become something like this: "cipher=sqlcipher&key=password123&legacy=4"
This is now working for me. I recommend that others use it if they are interested in an easy way to do sqlcipher version 4 similarly to how it is done in an android project.
I'm confused on how to send data to my database in Eclipse. I have Eclipse EE and I set up my database development correctly but I don't understand how to actually send the data in the database. I tried writing the mysql code inline with the Java but that didn't work so I'm assuming I'm doing it way wrong.
public void sendTime() {
String time = new java.util.Date();
INSERT INTO 'records' ('id', 'time') VALUES (NULL, time);
}
You actually need to do the following:
1) Install MySQL (presumably already done)
2) Download a MySQL JDBC driver and make sure it's in your Eclipse project's CLASSPATH.
3) Write your program to use JDBC. For example (untested):
private Connection connect = null;
private Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connect =
DriverManager.getConnection("jdbc:mysql://localhost/xyz?"
+ "user=sqluser&password=sqluserpw");
String query = "INSERT INTO records (id, time) VALUES (?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt (1, null);
preparedStmt.setDate (2, new java.util.Date());
preparedStmt.executeUpdate();
} catch (SQLException e) {
...
}
Here are a couple of good tutorials:
http://www.vogella.com/tutorials/MySQLJava/article.html
http://www.mkyong.com/jdbc/jdbc-preparestatement-example-insert-a-record/
This is a demo code for database use in JAVA
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name","uname","password");
Statement st = con.createStatement();
String stmt = "Type your sql INSERT statement here";
st.execute(stmt);
}
catch (Exception ex)
{
}
Here is a quick guide tutorial which you must read :-
http://www.tutorialspoint.com/jdbc/jdbc-quick-guide.htm
So a little background on my problem: I am trying to copy over a table on an Microsoft SQL system from an Oracle database. Besides giving password and user access to the table I cannot edit or do anything to the MSSQL database.
I successfully used the Oracle SQL Developer to connect and view the tables I want (using a third party JDBC driver), but I want to set up an automated copy-over into my Oracle database so I am attempting to use the same driver in some stored java code.
I have a java function that all it should do is go and count the number of entries in the table. So far my code looks like:
public static String getCount() {
Statement stmt = null;
Connection conn = null;
int rowCount = 0;
String message = "";
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.err.println("Error loading driver: " + e);
message = message + e + " -ER1 \n";
}
try {
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://site.school.edu:2000/ACCESS", "user", "password");
stmt = conn.createStatement();
String strSelect = "select 1 as field;";
ResultSet rset = stmt.executeQuery(strSelect);
while (rset.next()) {
++rowCount;
}
}
catch(SQLException ex) {
ex.printStackTrace();
message = message + ex.getSQLState() + " -ER2";
}
finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch(SQLException ex) {
ex.printStackTrace();
message = message + ex.getSQLState() + "-ER3";
}
}
return message;
}
Which is being calling from a stored function :
CREATE OR REPLACE function Schema.java_testMessage return varchar2
as language java
name 'ConnectAndQuery.getCount() return java.lang.String';
Which I am calling from a script in TOAD:
set serveroutput on;
declare
words varchar2(400);
begin
words := KSL_ADMIN.java_testMessage;
dbms_output.put_line(words);
end;
However the result is that I'm getting:
java.lang.ClassNotFoundException: net/sourceforge/jtds/jdbc/Driver -ER1
08001 -ER2
PL/SQL procedure successfully completed.
I have the jar file within the class path, I can't think of any reason it shouldn't have the nessecary permissions to see the jar, and as far as I can tell I have everything spelled correctly.
Please help me figure out what I am doing wrong. Or if there is perhaps an easier way to go about connecting an Oracle DB to an MSSQL DB without really installing anything. Any knowledge on this is welcome as I am pretty new to a lot of this.
Oracle has its own internal java virtual machine and it does not use the system classpath. If you need external libraries you must “load” them into the internal JVM. You can do this using Oracle's loadjava tool.
See the Oracle's loadjava documentation (http://docs.oracle.com/cd/B28359_01/java.111/b31225/cheleven.htm#JJDEV10060)
Guys,
I know there are some new features in JDBC4.0 and one of them is that you don't need to load database drivers explicitly as the JDBC API will automatically load the driver when you call getConnection(). So I just wanna test it.
BTW, I use Eclipse as my Dev Tool.
Here are my code snippets:
public class Test002JDBCRowSet {
public static void main(String[] args) throws Exception{
String connURL = "jdbc:oracle:thin:#192.168.1.150:1521:";
String database = "bmdw";
String userName = "bmdw";
String passWd = "bmdw";
String driver = "oracle.jdbc.driver.OracleDriver";
String SQLStr = "select t.Empno, t.Ename, t.job, t.sal from employer t where t.sal > 1500";
/*
try{
Class.forName(driver);
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}
*/
//Latest Method4 : Search for some data with RowSet, offline!
RowSetFactory rsf = RowSetProvider.newFactory();
try(
Connection conn = DriverManager.getConnection(connURL + database,userName,passWd);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQLStr);
CachedRowSet cachedRS = rsf.createCachedRowSet();){
cachedRS.populate(rs);
conn.close();
System.out.println("======Employee List -- Salary more than 1500======");
System.out.printf("%-15s%-15s%-15s%-15s%n","Employee No.","Employee Name","Employee Job","Employee Salary");
try{
while(rs.next()){
System.out.printf("%-15d%-15s%-15s%.2f%n",cachedRS.getInt(1),cachedRS.getString("ENAME"),cachedRS.getString("JOB"),cachedRS.getFloat(4));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
while(cachedRS.next()){
System.out.printf("%-15d%-15s%-15s%.2f%n",cachedRS.getInt(1),cachedRS.getString("ENAME"),cachedRS.getString("JOB"),cachedRS.getFloat(4));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
}
}
I got the runtime exception :
java.sql.SQLException: No suitable driver found for
jdbc:oracle:thin:#192.168.1.150:1521:bmdw
However, if I remove the comments about loading oracle driver explicitly, it works well.
And I'm sure I have already add the ojdbc14.jar into classpath.
So I don't know what happened. I'm trying to figure out how does the method 'getConnection()' works.
I checked System.getProperties() but there is no property named 'jdbc.driver'. Even if I added it and set the value to 'oracle.jdbc.driver.OracleDriver'. It still doesn't work.
I checked ClassLoader.getSystemResources("META-INF/services/" + Driver.class.getName()) and I found there is only one default file :
jar:file:/D:/Java/jdk1.7.0_03/jre/lib/resources.jar!/META-INF/services/java.sql.Driver
I has so far achieved little.
There might be some oversight in the configuration of Eclipse.
Hope anyone can help me.
Thanks.
I agree with #kordirko and his comment. OP also seems to have confirmed that his problem is resolved because of his comment. Hopefully he gets notification of this and makes it an answer. :)
Check this link: http://docs.oracle.com/cd/E11882_01/java.112/e16548/jdbcvers.htm#JJDBC28109 --> You need to have the ojdbc6.jar in your classpath environment variable in order to have JDBC 4.0 standard support. – kordirko
I am new to JDBC, and I wanted to find out if there is a way to check if a particular database already exists in MySQL.
Let's say I wanted to create a database named students. If the students database is already created in MySQL an error message in Eclipse would state that this students database already exists. However, I wanted to create a Boolean method to check if students database already exists. If it exists then the Boolean method would return false, otherwise if it’s true, then I can create the students database.
How do I do these in Java? Are there any methods in JDBC that does this or do I need to code it from scratch?
I followed mguymons suggestion and this is what I came up:
public boolean checkDBExists(String dbName) {
try {
Class.forName(JDBCDriver); // Register JDBC driver
System.out.println("Creating a connection...");
conn = DriverManager.getConnection(DBURL, USER, PASS); // Open a connection
ResultSet resultSet = conn.getMetaData().getCatalogs();
while (resultSet.next()) {
String databaseName = resultSet.getString(1);
if(databaseName.equals(dbName)) {
return true;
}
}
resultSet.close();
}
catch(Exception e) {
e.printStackTrace();
}
return false;
}
You can get that information from a JDBC Connection using getCatalogs. Here is an example of getting the Catalogs, aka Database names
// Connection connection = <your java.sql.Connection>
ResultSet resultSet = connection.getMetaData().getCatalogs();
// Iterate each catalog in the ResultSet
while (resultSet.next()) {
// Get the database name, which is at position 1
String databaseName = resultSet.getString(1);
}
resultSet.close();
show databases like 'students'
If you get a row back, it exists.
In newer versions of MySQL (5 and above) run this query:
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
If the result is 1 it exists.
In Java JDBC that would look something like this:
// Create connection and statement
String query = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema'[database name]' AND table_name = '[table name]'";
ResultSet rs = stmt.executeQuery(query);
rs.next();
boolean exists = rs.getInt("COUNT(*)") > 0;
// Close connection, statement, and result set.
return exists;
You're doing it back to front. The correct technique is to try to create it and catch the exception. The way you want to do it is subject to timing-window problems: it wasn't there when you tested, but it was there when you tried to create it. And you still have to catch the exception anyway.
You should break out of the loop once the target database is found. Otherwise, it's only sensible if your target search is the last in the result set.
public boolean checkDBExists(String dbName) {
try {
Class.forName(JDBCDriver); // Register JDBC Driver
System.out.println("Creating a connection...");
conn = DriverManager.getConnection(DBURL, USER, PASS); // Open a connection
ResultSet resultSet = conn.getMetaData().getCatalogs();
while (resultSet.next()) {
String databaseName = resultSet.getString(1);
if(databaseName.equals(dbName)) {
return true;
break;
}
}
resultSet.close();
}
catch(Exception e) {
e.printStackTrace();
}
return false;
}