I'm trying to connect to my sql database on localhost.
With the following code :
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(ClassNotFoundException e) {
System.out.println("JdbcOdbcDriver wasn't found");
e.printStackTrace();
}
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost/testBase", "root", "");
Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery("");
}
catch(SQLException e){ System.out.println(e); }
finally {
if(connection != null) {
try { connection.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
I have 2 questions related to this code :
I am using the sun.jdbc.odbc.JdbcOdbcDriver driver because it seem that it was the only available on my system, however I've read that it's a windows component... Is there a way to make it platform independent (or is it already) ?
The second catch outputs a
java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost/
Which is quite annoying and I don't seem to be able to find a way to work...
Thanks for your help !
When you generate jar, you can include all its dependencies.
So, you can use any driver you need and include it when you generate jar for the application.
Now you're cross platform.
About the question #2, that's because you don't have the mysqLconnector at lib folder.
You can download it here: http://dev.mysql.com/downloads/connector/j/
Just include it, if you're using IDE, you can look for a option "include jar/folder" and add it, then, try again; if you aren't in a IDE ... you have to set it on classpath.
Related
I have a Filename.sql(Mysql Script) file which has multiple SQL Statements. I'm using MyBatis as persistence framework and MySQL as the database. I want to execute the Filename.sql file in a Java program.
NOTE: I don't want to execute the queries as separate SQL Statements.
This operation is equivalent to source Filename.sql in MySQL command prompt.
you can use org.apache.ibatis.jdbc.ScriptRunner to do this:
ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
runner.setAutoCommit(true);
runner.setStopOnError(true);
runner.runScript(getResourceAsReader("Filename.sql"));
runner.closeConnection();
private void runMysqlScript(String sqlScriptFilePath) {
try {
// Create MySQL Connection
Class.forName(driverClassName);
Connection connection =
DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
// Initialize object for ScriptRunner
ScriptRunner runner = new ScriptRunner(connection);
// Give the input file to Reader
Reader br = new BufferedReader(new FileReader(sqlScriptFilePath));
// Execute script
runner.runScript(br);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
As an alternative you can try to use something like liquibase or something similar, which brings you a healthy way of versioning your scripts. In this case you need to convert your .sql-script into the liquibase one. Then you can execute it with Maven plugin or just from Java. It allows you to control the state of your data.
Otherwise, for DML and DQL types of queries you can use the ScriptRunner approach.
Hello there and thanks in advance for any reply,
I'm creating a restful web service and I would like to know:
How to execute a "table exporting query" from eclipse
the query works, it backs up the file, the only problem is it's not being executed for some reason from eclipse
Important to add, I'm using oracle's database express.
in sqlplus: $exp USERID=hr/password TABLES=(hr.students) FILE=exp_tab.dmp
from cmd: sqlplus /as sysdba
$exp USERID=hr/password TABLES=(hr.students) FILE=exp_tab.dmp
The method, where I attempted to execute such query is combined with anotherinsert query
My objective is to backup the table (to a file on a local drive) after every insert
note: Yes, I know I can create a trigger for that.
public static boolean insertUser(int id, String name, String gender, int grade) throws SQLException, Exception {
boolean insertStatus = false;
Connection dbConn = null;
try {
try {
dbConn = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt_backup = dbConn.createStatement();
Statement stmt = dbConn.createStatement();
String query = "INSERT into students(id, name, gender, grade) " +
"values('"+id+"',"+"'"+name+"','"+gender+"','"+grade+"')";
String query_backup = "$exp USERID=hr/password TABLES=(hr.students) FILE=exp_tab.dmp";
stmt_backup.executeQuery(query_backup);
stmt_backup.close();
//System.out.println(query);
int records = stmt.executeUpdate(query);
//System.out.println(records);
//When record is successfully inserted
if (records > 0) {
insertStatus = true;
}
} catch (SQLException sqle) {
//sqle.printStackTrace();
throw sqle;
} catch (Exception e) {
//e.printStackTrace();
// TODO Auto-generated catch block
if (dbConn != null) {
dbConn.close();
}
throw e;
} finally {
if (dbConn != null) {
dbConn.close();
}
}
return insertStatus;
}
PS: I've tried doing that with one statement , and got the same result.
Also I tried replacing executeQuery(query_backup);
with executeUpdate(Query_backup);
You did well to ask for help. That will save you a lot of time.
First point: You need to understand better what a Java DB connection is done for. In fact, I think, but maybe I am wrong, that your mistake shows a lack of architectural understanding about client / server architecture (DBMS in the present context).
Quick answer: You can only execute SQL statement through a client connection (whatever the technology you use for establishing that connection). So everything is good for your INSERT request but you cannot execute your sqlplus command through your JDBC connection.
Second point: I find a little bit strange for a web service to make a backup of a table. What do you really want to do?
Third point : if you want to execute a command line statement from Java, here is the solution (but in your case I think it is a bad idea):
public class NewClass {
final String userName = "myuser";
final String myPassword = "password";
public NewClass () {
String[] myCommandWithParams=new String[4];
myCommandWithParams[0]="sqlplus";
myCommandWithParams[1]="USERID="+userName+"/"+myPassword;
myCommandWithParams[2]="TABLES=(hr.students)";
myCommandWithParams[3]="FILE=exp_tab.dmp";
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(myCommandWithParams);
} catch (SecurityException | IOException ex) {
System.err.println("There is a problem for executing the command");
} catch (IndexOutOfBoundsException ex) {
System.err.println("myCommandWithParams can't be empty");
}
}
}
A remark : The Runtime.exec(String[]) doesn't take into account environment variables. If you want to set environment variables, you must use Runtime.exec(String[],String[]).
The second parameter corresponds to the list of environment variables you want to set. The syntax for these strings is "<VARIABLE_NAME>=<VALUE>". But it is easier to put the path of your sqlplus command in myCommandWithParams[0]. It is up to you to see what is best for you. I don't have the context.
There are many similar questions but I am closing the connection in the finally block. I am testing so I am refreshing the same page often.
in the DAO ( which is called from the controller when the view is accessed)
try {
con= DB.getConnection();
st= connection.createStatement();
rs = statement.executeQuery(MY_QUERY);
while (rs.next()) {
...
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
try { rs.close(); } catch (Exception e) { /* ignored */ }
try { st.close(); } catch (Exception e) { /* ignored */ }
try { conn.close(); } catch (Exception e) { /* ignored */ }
}
in application.conf
db.default.driver=org.postgresql.Driver
db.default.url="jdbc:postgresql://hostname2/schema"
db.default.user="myuser"
db.default.password="mypass"
Inevitably after a few hours coding I hit the no more connections error. shouldn't the finally close the connection and return it to myuser's pool? Does hitting CTRL-D not close the connection?
Using: PostgreSQL, Java with Play2 framework, running with play run (testing/building stage)
UPDATE: still looking for a reason
Here's some working database code from a project I'm working on:
try
{
//Run a query.
statement = connection.createStatement();
statement.execute(db_request);
results = statement.getResultSet();
//Put the list of names into the table.
table = getTableResults(results);
if(table == null)
return null;
System.out.println("Running database command: " + db_request);
//End.
results.close();
statement.close();
connection.close();
}
catch (SQLException ex)
{
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
return null;
}
return table;
I run all the close statements at the end of the try block and only catch SQLException. If anything else is going on, the console prints the stack trace and shows me the exact line where it broke.
By the way, catch(Exception e) is a REALLY bad coding practice that causes Java to hide errors from you unless they're fatal. I imagine you'd get a lot more information from the stack trace that's automatically printed to the console if you removed those lines.
Seeing how Play Framework gives you play.Logger class, you could instrument that finally and the try {} catch {} inside it with
Logger.info("Something happened...");
and start getting the idea of whats happening for yourself. From top of my head - nothing looks wrong with your code. Do you know the max number of concurrent connections that your db supports btw? If its running in the cloud, there may be an artificial limitation as well.
public void connect()
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:msql://23.249.225.135:3306/";
Connection conn = DriverManager.getConnection(url,"s****d","1*****-");
System.out.println("DB works");
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
I have the JDBC driver in the /lib folder in my class path.
Keep getting:
No suitable driver found for jdbc:msql://23.249.225.135:3306/
Any ideas?
You've misspelled mysql in the url is msql.
The version of your mysql database doesn't support the version of your driver or vice-versa.
Look for the compatibility matrix here: Chapter 2 Connector/J Versions
I am trying to connect to MS-Access using JDBC:ODBC:
public boolean connectToAccess(String accessFilePath) {
//Get connection to database
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
myConnection = DriverManager.getConnection("jdbc: odbc: driver={Microsoft Access Driver (*.mdb)};DBQ=" + accessFilePath);
} catch (Exception ex) {
System.out.println(ex);
return false;
}
return true;
}
I get the error:
"No suitable driver found for jdbc: odbc: driver={Microsoft Access Driver (*.mdb)};DBQ=file.mdb"
Why?
Can you suggest another way of reading access files in Java?
Take those spaces out of the connection string and see if that helps. I'd also recommend printing the stack trace.
public boolean connectToAccess(String accessFilePath) {
//Get connection to database
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
myConnection = DriverManager.getConnection("jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=" + accessFilePath);
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
The other way to read Access files is using the Jackcess library.
Try to create a DSN for the Access database from odbcad32. Another issue may be, the driver is not installed on your machine or you have insufficient privileges.