So I've been able to connect to MySQL through Netbeans on my older computer, using the following code:
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost:3306/tblpizza?user=root";
Connection con = DriverManager.getConnection(connectionUrl,"root","root");
However, since getting a new computer, every time I try to run the code, it comes up with this error:
SQL Exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown
database 'root'
Being fairly new to coding in general, I tried researching different queries online but couldn't come up with a solution.
Notes:
-I tried changing different sections of my code, making sure I didn't miss any upper case/lower case letters
-I went onto MYSQL and ran a command to check all the database names, and made sure to copy the right one down
-No matter how I change the code in anyway, it always says "unknown database 'root'" even though I haven't put root down as the database name
Any help would be greatly appreciated!
Your database URL should not have the ?user=root suffix.
Make it look like so, as you are specifying the username/password already in the getConnection(url, username, password) call.
String connectionUrl = "jdbc:mysql://localhost:3306/tblpizza";
Since it is asking from username and password in next step while making con object you should not specify it in connection url.
Try to run code by removing the ?user=root from your connection url.
String connectionUrl = "jdbc:mysql://localhost:3306/tblpizza";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tblpizza","root","root");
Try this way, you can omit the connectionUrl variable.
Related
I have an application that uses an embedded H2 database. I want to implement a backup and restore feature. I can successfully backup my data, but I get a hurdle when I try to restore it. This is how i'm backing it up:
String DBQ = "SCRIPT TO ?";
PreparedStatement myStatement = connection.prepareStatement(DBQ);
myStatement.setString(1, backupFile.getAbsolutePath());
myStatement.executeQuery();
I get my backup file generated just fine with the data. I can't seem to restore it however. This is how I try to restore it:
String DBQ = "RUNSCRIPT FROM ?";
PreparedStatement preparedStatement = connection.prepareStatement(DBQ);
preparedStatement.setString(1,unencryptedFile.getAbsolutePath());
preparedStatement.executeUpdate();
I get a org.h2.jdbc.JdbcSQLSyntaxErrorException: Sequence already exists. I've looked around and pretty much the only thing I could find on it was from 2013, with no answer Backup and Restore h2 and I'm sure my database isn't corrupted. I can't seem to find any documentation to help me resolve this too. How can I resolve this?
Here is an whole example how to backup+restore:
https://gist.github.com/cwdesautels/11188409
I saw a similar question asked:
Issue while creating Oracle ARRAY Type in java using ArrayDescriptor
However my issue is that other coders on the team are using the same code and apparently it is working fine for them.
Connection conn = null;
Connection oracleConn = null;
CallableStatement stmt = null;
try {
conn = this.getDataSource().getConnection();
if ( conn.isWrapperFor(oracle.jdbc.OracleConnection.class)) {
oracleConn = conn.unwrap(oracle.jdbc.OracleConnection.class);
}
I did not develop this code, I found it odd they're unwrapping an OracleConnection into a regular Connection class. Bawwwt.
I've tried a whole boat load of things, but really this code is supposed to work as is.
Now the above code generates a null pointer later on when a prepared statement is called since the if statement never fires. I never make it inside that if statement,
However when I force myself to do an unwrapping I get:
java.sql.SQLException: DSRA9122E: com.ibm.ws.rsadapter.jdbc.WSJdbcConnection#35c735c7 does not wrap any objects of type oracle.jdbc.OracleConnection
The environment is running ojdbc14 and JVM 6.0. Setup in WebSphere
First time poster, so I apologize in advance if I am mucking something up.
EditRemoved two variables from code that don't matter
Double check your config. Your DataSource must not be pointing to an Oracle DB like you think it is. I tested your code and it will work if your DataSource is truly pointing to an Oracle DB.
The isWrapperFor() method is trying to tell you that your Connection does not wrap OracleConnection, and that is also consistent with what the exception message is telling you.
You can check the datasource product information like this:
DatabaseMetaData metadata = conn.getMetaData();
System.out.println("DB product: " + metadata.getDatabaseProductName());
System.out.println("JDBC Driver: " + metadata.getDriverName());
I have added multiple jars(ojdbc6 for oracle and jtds-1.2.jar for sqlserver ) to my classpath.
When I test connection using following code :
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
if(conn==null){
System.out.println("false");
}
else{
System.out.println("true");
}
Scenario 1:
If I give JDBC_DRIVER as sqlserver URL (net.sourceforge.jtds.jdbc.Driver)
and DB_URL,USER,PASS for my oracle instance then also it will create connection for me but logically it is wrong.
Scenario 2:
If I give some other(not oracle.jdbc.driver.OracleDriver ) valid class in ojdbc6.jar and valid DB_URL,USER,PASS then also it will create connection .
But I always want to check valid JDBC_DRIVER which corresponds to the given DB_URL,USER,PASS
I have also tried registerDriver and deregisterDriver API available in driverManager. What are the pros and cons of using it.
Explanation for - Scenario 1/Scenario 2
From oracle documentation
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
So even you comment out Class.forName(JDBC_DRIVER); you will get the same result as ojdbc6 is in your classpath and in DriverManager.getConnection(...); method you are passing oracle database related information.So DriverManager always will return the connection instance for oracle daabase only.
Explanation for- want to check valid JDBC_DRIVER which corresponds to the given DB_URL,USER,PASS
For this you can use getDriver(String url) method of DriverManager class.
getDriver(String url)
Attempts to locate a driver that understands the given URL.
To check valid driver name try these lines below.
conn = DriverManager.getConnection(this.dbUrl, this.dbUser, this.dbPassword);
DatabaseMetaData dbMetaData = conn.getMetaData();
this.databaseProperties.add("Driver Name: " + dbMetaData.getDriverName());
I am looking for a way to save an SQL database and then reference it by means other than localhost which would not work because it is being used on other computers.
I realize that my terminology may not be correct in asking for a means to "package" an SQL database however I am not very sure how to put my desire such a concise title.
I have a database that I created through mySQL here: http://gyazo.com/fcac155a60c0d2587442c3e4807ef98a
I can access this database with no problems through the following code...
try
{
//Get connection
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/term_database","root", "_cA\"#8X(XHm+++E");
//**********
//Connection myConn = DriverManager.getConnection("jdbc:mysql:translationDatabase","root", "_cA\"#8X(XHm+++E");
//**********
//create statement
Statement myStmt = myConn.createStatement();
//execute sql query
ResultSet myRs = myStmt.executeQuery("select * from terms WHERE idNumber=" +termNumber);
//process result set
while(myRs.next()){
term= (myRs.getString(language));
}
}
catch (Exception exc)
{
exc.printStackTrace();
}
However, I assume that my users will be on different computers and so a "//localhost" reference will not work. They do not have access to the internet either. So I aim to include the database in my program's files to be downloaded with the software or to include it in the jar. I was not able to find any means to do that online. The code I surrounded with *'s was an attempt to reference translationDatabase.sql which I saved through the program mySQL into my software's directory but it did not work as shown here: http://gyazo.com/e9d4339435dedecab4e7ad960e9b13b6
To recap: I am looking for a way to save an SQL database and then reference it by means other than localhost which would not work because it is being used on other computers.
The idiomatic terminology is "embedded" or "serverless" database.
There are several pure-java solutions. There is also the popular SQLite, which you can manipulate via its command line client, or via a third-party JDBC driver (example 1, example 2)
Any of the above solutions will require that you convert your existing MySQL database to the target system..
Alternatively, you may consider bundling your application with MySQL server (possibly with an automated installation process, so that installation is invisible to the end-user).
I am working on a functionality where i need to check whether database is down or not. i have to use single query which works for both oracle and sqlserver dbs. is there any single query which checks whether db is up or not?
similar to select * from dual;
Thanks!
I'd go with a connection.setAutoCommit(true) and not with a select.
I think it would be best to use the Connection's function to check the server is available.
There should be an Exception when it fails to connect and you can check the state to see if it's still open.
To address your specific need, if you decide to continue with a query.
THIS IS NOT BEST PRACTICE
I don't know of a simple way to do what you wish, Oracle and SQL don't share the same naming for system objects. BUT run that command, it won't work on SQL, but the exception won't be of type 'Server is Down' and you can use it in your try/catch.
THIS IS NOT BEST PRACTICE
Hope it makes sense.
Better way is to obtain the connection and then use the database metadata information like the product version or product name to ensure the database is up or not.
Eg:
try{
Con = DriverManager.getConnection(databaseURL,username,password);
databasemetadata = con.getMetaData();
String databaseName = databasemetedata.getDatabaseProductName();
If(databaseName.equals("<desireddabase>"))
{
//database up and running
}
}
catch(Exception e)
{
// error in connection ...
}
The java.sql.Connection has a method
isValid(timeOut)
Returns true if the connection has not been closed and is still valid. The driver shall submit a query on the connection or use some other mechanism that positively verifies the connection is still valid when this method is called.