How to determine which driver to use for JDBC - java

I ran the following codes in Netbeans attempting to connect to MySQL database.
package database_console;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class DBConnect
{
public static void main(String[] args)
{
try{
String host = "jdbc:mysql://localhost:3306/mydatabase";
String uName = "root";
String uPass = "password";
Connection con = DriverManager.getConnection( host, uName, uPass );
Statement stmt = con.createStatement();
String sql = "SELECT * FROM counselor";
ResultSet rs = stmt.executeQuery(sql);
rs.next();
int id_col = rs.getInt("id");
String first_name = rs.getString("firstName");
String last_name = rs.getString("lastName");
String p = id_col + " " + first_name + " " + last_name;
System.out.println(p);
}
catch(SQLException err){
System.out.println(err.getMessage());
}
}
}
I get the following exception message:
No suitable driver found for jdbc:mysql://localhost:3306/mydatabase
I know that I have to go to my project folder and add a JAR in my libraries folder. I've read through numerous online guides, however none talks about how to determine which JAR file is suitable.
So my question here is: Can I just get any JAR file and use it as a client driver? For example derbyclient.jar? If not, is there any way to identify which JAR file is suitable to use as a client driver?
EDIT: Furthermore, I am a little confused whether I should download the required driver from Sun Microsystem, Netbeans, MySQL.

I have encountered this error and this is how i solved it.
1)Go to Properties of your project
2)Go to Libraries
3)Add Library
4)Select MySQL JDBC Driver
This worked for me.

Go to your netbeans->Project->Properties.
In the libraries "Add Library".
Select MYSQL JDBC Driver.

You need to include a JAR in your classpath.
For Mysql, for e.g.- mysql-connector-java-5.1.18-bin.jar
If you are using maven, dependency in POM.xml would be
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
You need to register a driver, before getting connection using DriverManager.getConnection as follows
Class.forName("com.mysql.jdbc.Driver");

The JDBC driver is a connector specific to the database. In your case, you'll need the MySQL JDBC connector.

You need to know the kind of database you are connecting to while preparing the host url.
In the example pasted
String host = "jdbc:mysql://localhost:3306/mydatabase"; The string "mysql" indicates its a mysql database. Hence you need to use mysql client library.

You need to decide based on the Database that you have used.
In your case you have used MySQL so you need to use jdbc driver for MySQL.
http://dev.mysql.com/downloads/connector/j/
If you are using Oracle then you can use jdbc driver provided by Oracle.
http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html
You can find jdbc driver on your chosen DB's official website. It is dependent on the JDK version as well as DB version.

Related

Set relative path using jdbc, on a sqlite DB on user computer

I'm trying to build a simple java application for my school project, and I want to be able to use a simple DB, in order to insert, update, delete and ask queries on my DB.
I need my application to run everywhere on installation, so I want to use a local DB that ships with my application, and will be accessible from inside the project, without different DB dependencies
so I've read a little and found this SQLite tutorial -http://www.sqlitetutorial.net/sqlite-java/sqlite-jdbc-driver/
,
now I want to set a relative path to the user who download my application, and set the connection on the user computer. I've noticed it's written :
connect to an in-memory database, you use the following connection string:
jdbc:sqLite::memory
here is my code:
public class Main {
public static void main(String[] args) {
try{
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Desktop\\School Project\\Software-Engineering---Java-Project\\data.db");
Statement statement = conn.createStatement();
//CREATE TABLES
statement.execute("CREATE TABLE IF NOT EXISTS CUSTOMERS (name TEXT,phone INTEGER,email TEXT)");
//INSERT TO TABLES
statement.execute("INSERT INTO CUSTOMERS (name,phone,email)" +
"VALUES ('NETANEL', 05555555,'SADF#GMAIL')");
notice how my JDBC is the path to my local computer, how can I change this?
EDIT:
I'm able to set the path with only referring the DB name:
final static String DB_URI = "jdbc:sqlite" + ":data.db";
public static void main(String[] args) {
try{
Connection conn = DriverManager.getConnection(DB_URI);
Statement statement = conn.createStatement();
the question is, will it be cross platform if i will deploy my application with this DB?
You can use the user home directory. You are sure it's always defined whatever platform you deploy your program on, and your program will have read/write access to it.
Something like this:
String dbUri = "jdbc:sqlite:" + System.getProperty("user.home") + "/data.db";
Connection conn = DriverManager.getConnection(dbUri);

How to create tables from jdbc program in hortonworks using Hive?

I want to create table in Hive by using JDBC. This is the code I tried,
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class HiveClient {
private static String driverName = "com.mysql.jdbc.Driver";
public static void main(String[] args) {
Connection con=null;
// Register driver and create driver instance
try {
Class.forName(driverName);
// get connection
con = DriverManager.getConnection("jdbc:mysql://sandbox-hdp.hortonworks.com/hive?createDatabaseIfNotExist=true/userdb", "root", "dc123");
// create statement
Statement stmt = con.createStatement();
// execute statement
stmt.executeQuery("CREATE TABLE IF NOT EXISTS "
+" employee ( eid int, name String, "
+" salary String, destignation String)"
+" COMMENT ‘Employee details’"
+" ROW FORMAT DELIMITED"
+" FIELDS TERMINATED BY ‘\t’"
+" LINES TERMINATED BY ‘\n’"
+" STORED AS TEXTFILE;");
System.out.println(" Table employee created.");
con.close();
}catch(Exception e){
System.out.println(e);
}
}
}
This program shows an Exception:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver.
Please help me to solve this issue.
First of all, you've copied code from a MySQL connection example, and tried to replace the query with HiveQL, which will not work.
Neither com.mysql.jdbc.Driver or jdbc:mysql will let you connect to Hive.
See Hive wiki on Using JDBC to connect to Hive.
The error simply means your classpath doesn't have the MySQL Driver on the classpath. Even if you changed the string, you'd get a similar error for Hive.
I strongly suggest using Maven or Gradle to load your dependencies.
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>1.2.1</version>
</dependency>
Additionally sandbox-hdp.hortonworks.com/hive needs a port number like sandbox-hdp.hortonworks.com:10000/hive plus you do not need ?createDatabaseIfNotExist=true/userdb. Nor are the user credentials for Hive root/dc123 on the sandbox.
If you are trying to connect to the Hive metastore, which I believe is running PostgreSQL in the Hortonworks Sandbox, then again, you're using the wrong JDBC driver, connection URL, query syntax, and server port information.
Changing the connection string worked for me
Connection con = DriverManager.getConnection( "jdbc:hive2://58.184.82.67:10000/default", "", "");
In pom.xml added 3 dependencies,
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-auth</artifactId>
<version>2.7.3</version>
</dependency>

Moving from MySQL to MS Azure SQL Database

I have a J2EE web application that issues parameterized SQL queries to a MySQL back-end. I need to replace the back-end with MS Azure SQL Database. I have migrated the DB and data over to MS Azure SQL Database. However all my queries from the app are failing. For example the following query (shown with the wrapping code) runs perfectly fine in the Management Studio but fails in the java code:
PreparedStatement statement = dbConnection.prepareStatement("SELECT * FROM [mydb].[apps] WHERE [key] = ?;");
statement.setString(1, appKey);
ResultSet resultSet = statement.executeQuery();
The error I get is:
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'key'.
I tried various things like removing the [], qualifying the column name with the table name, etc. but nothing works.
Also one more question: The JDBC connection I am using string includes the database name (mydb) so I don't want to include it in each of my SQL statement. I never did for MySQL so I'd rather avoid doing it now since it would require me to manually add the DB name to each statement in the code. However if I remove the DB name from the above query it again fails with error Invalid object name 'apps'. Why isn't the DB specified in the connection string being used as the default one? The connection string I am using is jdbc:sqlserver://{servername}.database.windows.net:1433;database=mydb;user={username}#{servername};password={password};encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;
BTW I am using the Azure SQL Database V12 and connecting via Microsoft JDBC Driver 4.2 for SQL Server.
I tried to reproduce your issue, but my sample code ran fine. Per my experience, I think that the issue cause is by using incorrect table name form.
The MSSQL table name completed form is <db_name>.<owner_name>.<table_name>. Its short form could be <owner_name>.<table_name> or <table_name>. The item can be <item> or [<item>].
Sample Code (for Azure SQL Database, the same principle as MSSQL on Azure VM):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String jdbcUrl = "jdbc:sqlserver://<host_name>:1433;database=<db_name>;";
//The completed connection string is jdbc:sqlserver://<host_name>:1433;database=<db_name>;user=<user like username#server_name>;password={your_password_here};encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;
String user = "<user>";
String password = "<password>";
Connection conn = DriverManager.getConnection(jdbcUrl, user, password);
String sql = "SELECT * FROM person WHERE name = ?;" // My test table is 'person'
// The table name could be person, [person], dbo.person, [dbo].[person], <db_name>.dbo.person, [<db_name>].[dbo].[person]
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "Peter Pan");
ResultSet rs = statement.executeQuery();
while(rs.next()) {
System.out.println(rs.getLong("id")+","+rs.getString("name"));
}
}
}
I suggest you to use the third-party Universal Database Management Tool "Dbeaver". It based on Eclipse and used JDBC Driver to connect kinds of Database include MSSQL. You can create db connection to MSSQL on Azure VM and test SQL queries.
Best Regards.

Creating/Configuring Derby JDBC Client in IntelliJ Idea 13

Sorry for this (maybe) stupid question.
I need to create some local DB in my java project so I've decided for Apache Derby Client. I am working with IntelliJ IDEA 13 Ultimate and my problem is that I don't know, how to create local database.
Tutorials at Jetbrains websites aren't useful because there are articles only about connecting to the remote DB, not to the local one (or at least I didn't find them yet).
What have I done so far:
I've tried to set the DB up by creating new remote derby data source.
Screenshot with the settings: DB Settings screen
Username and password are the same: admin
After clicking test connection, this error is thrown: error
When I click apply and ok, it says that it's connected, but exception is still there.
So do you have any idea where the problem can be?
I've got small confiuration class called DatabaseSetting.java
package issuetrackinglite;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseSetting {
private String dbURL = "jdbc:derby://localhost:1527/MallDB;create=true";
private String user = "admin";
private String password = "admin";
private Connection connection;
public static final String CREATE_ITEMS_DB = "CREATE TABLE items (item_id INTEGER NOT NULL, item_name VARCHAR(20) NOT NULL, item_price REAL NOT NULL, multiplicity_shop INTEGER NOT NULL, multiplicity_store INTEGER NOT NULL)";
public static final String INSERT_PRODUCT = "INSERT INTO items (item_id, item_name, item_price, multiplicity_shop, multiplicity_store) VALUES (?, ?, ?, ?, ?)";
public static final String CLEAR_ITEMS_DB = "DELETE FROM items";
// -------------------------------------------------------------
protected Connection connectToDB() {
try {
connection = DriverManager.getConnection(dbURL, user, password);
return connection;
} catch (SQLException ex) {
System.out.println("SQL exception - connectToDB(): " + ex.getMessage());
return null;
}
}
}
EDIT
Simply explained: I just need to create virtual derby database which will be created every time at the program start.
I don't know, how to do it in IntelliJ.
I've added DERBY_HOME to the enviroment variables and also added path to Derby. Now this error is thrown by IntelliJ: Error window
Thank you very much for your help and time
I've managed to get this work. Here are the steps that I've made to successfully configure local Derby database to work in IntelliJ Idea 13/14.
First, you need to manually start derby server (if it is not already running) before using it in IDEA. I usually do it via command prompt by typing:
C:\Users\PcName>startNetworkServer -noSecurityManager
This command will start derby server on port number: 1527. Make sure you have correctly set path in enviroment variables
Next go to IDEA, open Database window, click on the green plus sign in the upper left corner and in the dropdown menu choose: Data Source -> Derby -> Remote
You can inspire with my settings provided in the screenshot in my question. You can also download Derby driver files. IDEA does it just by clicking on the download button.
Basic template which I always use is something like that:
Name field should be in the form: Derby - YourDatabaseName;create=true#localhost
Host field should have localhost inside
Port has to be 1527
Database field has to be in form: YourDatabaseName;create=true
Urc to connect: jdbc:derby://localhost:1527/YourDatabaseName;create=true
(Optional) - You can specify your database user name and password. In IDEA 14 there is a checkbox Save on disk with master password protection, which I personally always leave unchecked.
That's it. I hope this little guide will help somebody to configure Derby in Intellij IDEA
For embedded database, use the default/In-Memory/URL only select box on the right side of the connection URL input field. When set to In-Memory, it generates the following URL, which works for me.
jdbc:derby:memory:MallDB;create=true
I think that for a local (embedded) database, you would leave off the host and port in the connection url.
The documentation says that the url should be of the form: jdbc:derby:MallDB;create=true

JDBC Thin Connection

I have installed NetBeans 6.5 with JDK1.6. And I want to connect between oracle with java in NetBeans 6.5. The question is:
How do I configure JDBC to java 1.6?
Thanks,
Sopolin
Download page for Oracle JDBC driver and Oracle JDBC examples. Also see Sun's JDBC tutorial.
You need to download the Oracle thin JDBC driver and pop it on your classpath.
See this for a code example.
http://w2.syronex.com/jmr/edu/db/oracle-and-java
Here's the hints:
1.download the proper ORACLE DB driver version from following sites:
http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html
and import into the libary of Netbeans if you use NETBEANS as IDE.
2.In your Java code, define appropriate JDBC connections statement like that:
public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver" ;
public static final String DBURL = "jdbc:oracle:thin:#localhost:1521:Your_DB_NAME";
public static final String DBUSER = "YOUR ORACLE DB ID" ;
public static final String DBPASS = "YOUR ORACLE DB PASSWORD" ;
Connection conn = null ; // DB CONNECTIONS
PreparedStatement pstmt = null ;// DB OPERATIONS
ResultSet rs = null ; // save the query result
Class.forName(DBDRIVER) ; // Load the ORACLE DRIVER
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;
String sql = "SELECT name FROM client" ; //sample query
pstmt = conn.prepareStatement(sql) ; // execute the query and save the result
// the above cope snippet is the main things of JDBC.
//Hope it helps!

Categories

Resources