JDBC Thin Connection - java

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!

Related

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.

How to determine which driver to use for JDBC

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.

OraclePreparedStatement Method setStringForClob in java

I tried to insert CLOB in Oracle DB using below code.
I found the below code from this link
but setStringForClob is not available , Please let me know What am doing as Wrong.
am using oracle driver ojdbc14.jar and jdk 1.5
String sql = "insert into table values('abc',123,?)";
OraclePreparedStatement st = (OraclePreparedStatement) connection.prepareStatement(sql);
st.setStringForClob(1, /*String variable which contains the CLOB string*/);
Try getting a newer JDBC driver ojdbc14.jar is really old. Use ojdbc6.jar from oracle.

Setting the mysql collation correctly

I'm trying to insert to my table hebrew values but the result is always "??????".
Which collation should I use?I tried to use hebrew_bin and hebrew_general_ci and the result was the same.
The reason I used the Java tag is that my code is written in java and as far as I know in web development you have to specify the collation in the web scripts also.
So maybe I have to do that in the java code also?
EDIT
Here is the code:
private String url = "jdbc:mysql://ip:port/";
private String dbName = "dbname";
private String driver = "com.mysql.jdbc.Driver";
private String userName = "user";
private String password = "password";
....
stmt = conn.prepareStatement("INSERT INTO locations(location) VALUES (?)");
stmt.setString(1, "hebrew sentence");
stmt.execute();
Now how do I change my code into the example you showed?
As per a possible duplicate you might try this:
Posted by: Sai Ye Yan Naing Aye:
Set UTF-8 in your code. See the following:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/embeddedChat?" +
"user=site_access&password=XXXXXXXX&useUnicode=true&characterEncoding=UTF-8");
Personalized to your connection of course
See the following:
Connecting to MySQL Using the JDBC DriverManager Interface
JDBC Basics - Establishing a Connection
set the table you needed to utf8 and all the rows in it to
utf8 the added this to the connection script:mysql_query("SET NAMES 'utf8'");
This will help you I guess

How to check, that we are using oracle 8i database in jdbc?

In jdbc, how to check, that we are using oracle 8i database?
Connection connection = DriverManager.getConnection(url);
DatabaseMetaData meta = connection.getMetaData();
String product = meta.getDatabaseProductName();
String major = meta.getDatabaseMajorVersion();
String minor = meta.getDatabaseMinorVersion();
You might have to use the Database metadata class.
Run:
select * from v$version
It should produce something like:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
PL/SQL Release 10.2.0.4.0 - Production
...
Then it's just a simple matter of parsing that 1st result row.

Categories

Resources