Java database connectivity
Hi
Iam new to jdbc I have to connect java with my sql, could any one please guide me that fom where I can install mysql driver and which one and how to install it and what code needed to include in java programm, i have erade manual but being confused because seen differnt code at differnt places, plz help me.
thanks
Hi...
1) First install MySql
2) Obtain MySql JDBC Driver --> (http://www.mysql.com/get/Downloads/Connector-J/mysql-connector-java-3.0.9-stable.zip/from/pick)
3) Add downloaded driver to your Java Proyect library (../lib).
4) Make Connection
example:
Data base url: "jdbc:mysql://ANY_HOST/DB_NAME?user=dbUserName&password=dbPassword"
Load Driver: "org.gjt.mm.mysql.Driver"
then connect method can be:
private void doConnect()throws Exception{
// db url
String dbUrl= "jdbc:mysql://localhost/test?user=admin&password=admin";
try{
// load MySql driver
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
// request one connection
this.connection =DriverManager.getConnection(dbUrl);
}catch (Exception e) {
// do something
return;
enjoy ! ;-)
Similar Messages
-
JDBC is the Acronym of Java Database Connectivity - Yes / No?
Hi,
JDBC is the Acronym of Java Database Connectivity - Yes / No?
I am little bit confused. I got this question in an Inteview.
I support yes. But some of the compitiors say no.
What will the real answer?Really? Even Sun contradicts themselves here:
(2002) http://java.sun.com/javase/6/docs/technotes/guides/jdbc/
and (more importantly) here:
http://java.sun.com/docs/glossary.html#JDBC
although here:
(2001) http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/intro.html
I think it is simply silly for the latter to state that "JDBC is the trademarked name and is not an acronym" -- Oh really? JDBC doesn't stand for anything? It is all caps just because it is a trademark then? hmmm.
I'm certain the real answer of what it stands for may have been lost long ago. However, I doubt that the interviewer meant the question to be a trick and was looking for "Java DataBase Connectivity"
For every instance that you find that it doesn't stand for anything, I can show you 2 instances (from Sun or an employee) where they use "Java Database Connectivity (JDBC)".
P.S. Ryan Craig may be the final authority on this... -
How we build Java Database Connectivity for Oracle 8i Database
Can any one send me a sample code for Java Database Connectivity for Oracle 8i Database
it will be a grat help
Thanks & Regards
RasikaYou don't need a DSN if you use Oracle's JDBC driver.
You didn't read ANY of the previous replies. What makes you think this one willk help? Or any instruction, for that matter?
Sounds like you just want someone to give it to you. OK, I'll bite, but you have to figure out the rest:
import java.sql.*;
import java.util.*;
* Command line app that allows a user to connect with a database and
* execute any valid SQL against it
public class DataConnection
public static final String DEFAULT_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
public static final String DEFAULT_URL = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\Edu\\Java\\Forum\\DataConnection.mdb";
public static final String DEFAULT_USERNAME = "admin";
public static final String DEFAULT_PASSWORD = "";
public static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
public static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/hibernate";
public static final String DEFAULT_USERNAME = "admin";
public static final String DEFAULT_PASSWORD = "";
/** Database connection */
private Connection connection;
* Driver for the DataConnection
* @param command line arguments
* <ol start='0'>
* <li>SQL query string</li>
* <li>JDBC driver class</li>
* <li>database URL</li>
* <li>username</li>
* <li>password</li>
* </ol>
public static void main(String [] args)
DataConnection db = null;
try
if (args.length > 0)
String sql = args[0];
String driver = ((args.length > 1) ? args[1] : DEFAULT_DRIVER);
String url = ((args.length > 2) ? args[2] : DEFAULT_URL);
String username = ((args.length > 3) ? args[3] : DEFAULT_USERNAME);
String password = ((args.length > 4) ? args[4] : DEFAULT_PASSWORD);
System.out.println("sql : " + sql);
System.out.println("driver : " + driver);
System.out.println("url : " + url);
System.out.println("username: " + username);
System.out.println("password: " + password);
db = new DataConnection(driver, url, username, password);
System.out.println("Connection established");
Object result = db.executeSQL(sql);
System.out.println(result);
else
System.out.println("Usage: db.DataConnection <sql> <driver> <url> <username> <password>");
catch (SQLException e)
System.err.println("SQL error: " + e.getErrorCode());
System.err.println("SQL state: " + e.getSQLState());
e.printStackTrace(System.err);
catch (Exception e)
e.printStackTrace(System.err);
finally
if (db != null)
db.close();
db = null;
* Create a DataConnection
* @throws SQLException if the database connection fails
* @throws ClassNotFoundException if the driver class can't be loaded
public DataConnection() throws SQLException,ClassNotFoundException
this(DEFAULT_DRIVER, DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD);
* Create a DataConnection
* @throws SQLException if the database connection fails
* @throws ClassNotFoundException if the driver class can't be loaded
public DataConnection(final String driver,
final String url,
final String username,
final String password)
throws SQLException,ClassNotFoundException
Class.forName(driver);
this.connection = DriverManager.getConnection(url, username, password);
* Get Driver properties
* @param database URL
* @return list of driver properties
* @throws SQLException if the query fails
public List getDriverProperties(final String url)
throws SQLException
List driverProperties = new ArrayList();
Driver driver = DriverManager.getDriver(url);
if (driver != null)
DriverPropertyInfo[] info = driver.getPropertyInfo(url, null);
if (info != null)
driverProperties = Arrays.asList(info);
return driverProperties;
* Clean up the connection
public void close()
close(this.connection);
* Execute ANY SQL statement
* @param SQL statement to execute
* @returns list of row values if a ResultSet is returned,
* OR an altered row count object if not
* @throws SQLException if the query fails
public Object executeSQL(final String sql) throws SQLException
Object returnValue;
Statement statement = null;
ResultSet rs = null;
try
statement = this.connection.createStatement();
boolean hasResultSet = statement.execute(sql);
if (hasResultSet)
rs = statement.getResultSet();
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
List rows = new ArrayList();
while (rs.next())
Map thisRow = new LinkedHashMap();
for (int i = 1; i <= numColumns; ++i)
String columnName = meta.getColumnName(i);
Object value = rs.getObject(columnName);
thisRow.put(columnName, value);
rows.add(thisRow);
returnValue = rows;
else
int updateCount = statement.getUpdateCount();
returnValue = new Integer(updateCount);
finally
close(rs);
close(statement);
return returnValue;
* Close a database connection
* @param connection to close
public static final void close(Connection connection)
try
if (connection != null)
connection.close();
connection = null;
catch (SQLException e)
e.printStackTrace();
* Close a statement
* @param statement to close
public static final void close(Statement statement)
try
if (statement != null)
statement.close();
statement = null;
catch (SQLException e)
e.printStackTrace();
* Close a result set
* @param rs to close
public static final void close(ResultSet rs)
try
if (rs != null)
rs.close();
rs = null;
catch (SQLException e)
e.printStackTrace();
* Close a database connection and statement
* @param connection to close
* @param statement to close
public static final void close(Connection connection, Statement statement)
close(statement);
close(connection);
* Close a database connection, statement, and result set
* @param connection to close
* @param statement to close
* @param rs to close
public static final void close(Connection connection,
Statement statement,
ResultSet rs)
close(rs);
close(statement);
close(connection);
}% -
Java database connection method class for review
Can you guys tell me any specific coding standard has to be followed here(i guess i need not hard code the pwd's)
import java.sql.*;
public class DBLocator {
* Obtains and returns a connection to database
* @return database connection
public static Connection getConnection() {
Connection con = null;
try {
Class.forName("com.informix.jdbc.IfxDriver");
String url = "jdbc:informix-sqli://151.140.160.201:1527/ssde_db:INFORMIXSERVER=ssde_infx";
con = DriverManager.getConnection(url,"haha06","123123");
} catch (ClassNotFoundException e) {
System.out.println("Driver not found");
} catch (SQLException e) {
System.out.println("SQL exception");
e.printStackTrace();
return con; // returns connection
}Can you guys tell me any specific coding standard has
to be followed here(i guess i need not hard code the
pwd's)More than just the passwords. Why are the driver class and URL hard-coded?
I wouldn't use this class. It's not very useful as written. It's a poor abstraction for one. There's lots of other useful things that you could include, like methods for closing and rolling back a connection, closing a statement and result set. You don't log any exceptions or messages. You preclude the use of a connection pool managed by an Java EE app server.
% -
Problem in SQL Server 2000 Driver for Java Database Connectivity
Hi,
I have problem with MS SQL 2000 JDBC driver. I am using Type-4 driver for my application. I can able to connect through DSN. If I use Type-4 Driver to connect database means it gives the following exception.
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Error establishing socket.
at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source)
at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSConnection.<init>(Unknown Source)
at com.microsoft.jdbc.sqlserver.SQLServerImplConnection.open(Unknown Source)
at com.microsoft.jdbc.base.BaseConnection.getNewImplConnection(Unknown Source)
at com.microsoft.jdbc.base.BaseConnection.open(Unknown Source)
at com.microsoft.jdbc.base.BaseDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at test.TestDB.main(TestDB.java:17)
My Java Code :
String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
Class.forName(driver);
Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://192.168.48.90:1433;User=sa;Password=sa;DatabaseName=GWCANADA");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from emp");Do we have any other jdbc driver to connect MS SQL 2000 aprt from the Microsoft JDBC driver.
Plese help me to resolve this problem
Thanks
---SureshSame problem is here: http://forum.java.sun.com/thread.jspa?threadID=419214&tstart=135
Check that your server is running (telnet <hostname> 1433)
--Xapp -
Java Database Connections couldn't be closed on PI 7.1 EHP1
Hi, I develop a dynamic web project to PI. And I use Database conection in that web project. Even I closed the connection in java , Connection doesn't closed and after a while PI pooling size reach the maximum size and PI doesn't response. I find open connections on MSSQL and connections' status are sleeping, cmd fields are AWAITING COMMAND. I have to restart PI these to close that connections.
I get Connections like these code
InitialContext cxt = new InitialContext();
final DataSourceManager dsm = (DataSourceManager) cxt
.lookup("dbpool");
String lookUpName = dsm.getSystemDataSourceDescriptor().getDataSourceName();
DataSource ds = (DataSource) cxt.lookup("jdbc/" + lookUpName);
ds.setLoginTimeout(60);
conn = ds.getConnection();...
and I close connections like these
conn = db.getDefaultDatabaseConnection();
if (conn != null) {
try {
conn.setAutoCommit(true);
String sql = "INSERT INTO
pstmt.close();
conn.close();
} catch (Exception e) {
} finally {
try {
pstmt.close();
conn.close();
} catch (SQLException e2) {
e.printStackTrace();
e.printStackTrace();
I changed system DataSource's and i give these parameters
Initial Connections: 5
Maximum Connections: 125
Maximum Time to Wait for Connection: 90
Connection Lifetime (Sec.): 60
Cleanup Interval (Sec.) : 90
it didn't work either
Can anyone hepl me ?I would like to make slight changes in code. . Please close the resources only in finally block.
Dont know you are closing resultset or not. If not, you must close it
conn = db.getDefaultDatabaseConnection();
try {
if (conn != null) {
conn.setAutoCommit(true);
String sql = "INSERT INTO
} catch (Exception e) {
} finally {
try{
if(rs != null){
rs.close()
}catch(SqlException se){
//log it
try{
if(stmt != null){
stmt.close();
}catch(SqlException se){
//log it
try{
if(conn != null){
conn.close();
} catch(SQLException ss){
// log it
} // end of finally
Hope this help. -
Java Database Connectivity: No suitable driver
Hello,
for school I have to make a program that reads from a database and puts the data in an XML file.
I'm using Corel Paradox 10 for the database. I've configured the ODBC driver correctly as far as I can tell, but when I start the program it keeps saying:
SQL Exception:
SQL state: 08001
message: no suitable driver
vendor: 0
The following is the way I configured the driver in corel's BDE administrator:
type Microsoft Paradox Driver (*.db)
ODBC DSN ParadoxDump
There's more settings, but I doubt that that can have anything to do with it, it's mostly numbers and the username.
Now with the datasources (ODBC) in the windows configuration I have; with both the file-, system-, and the user-DSN the driver from Microsoft for Paradox, all named ParadoxDump, the file being in the directory where the tables are located, the complete filename is ParadoxDump.dsn.
This the section of my code that deals with the connection:
public class DumpUtility
public static void main(String args[])
try
Connection connection = DriverManager.getConnection("jdbc:odbc:ParadoxDump");
Statement statement = connection.createStatement();
Does anyone have any idea why Java can't find the driver, or why the driver is not suitable? If so, does anyone know a away to solve my problem? Whether that be code, reconfiguring the drivers or where I can find a suitable driver and how to configue it if my solution really can't work?Looks to me like you forgot to load the driver class. You need to load the driver explicitly, usually using Class.forName("driver.class.here") - that causes the class to register itself with the DriverManager. Then when you call getConnection it uses the URL string (in this case, "jdbc:odbc:ParadoxDump") to search through all the loaded drivers looking for one that recognizes that URL. That's how it knows which driver to use. With no driver loaded, the DriverManager class can't match that URL to a registered driver and that's what it's telling you.
--PF -
Question about java dataBase connectivity
Hello,
How could I get the name of a column from a table in dataBase ?
In my code i have :
ResultSet rss = selectTempo.executeQuery("SELECT LAST_INSERT_ID() AS LAST");
if(rss.next()){
firstColumn= rss.getInt("LAST");
How could i get the name of LAST in my table ?You can probably use the ResultSetMetaData class:
In you example it might go something like:
ResultSet rss = selectTempo.executeQuery("SELECT LAST_INSERT_ID() AS LAST");
ResultSetMetaData meta = rss.getMetaData();From there you can use the different methods that are available in the class. In you case, I think getColumnLabel() should do the trick. -
AIR application and database connectivity (using JAVA)
Hi
I am creating AIR application and I want to connect with the database using java database connectivity (JDBC).
Can any body give me the some suggestion on how to how to do that.
Please give me any reference for creating AIR application for database connectivity with mysql/access.
Thanks
Sameerlots of serching on the google and found that For AIR applications either you use Webservices(JAVA/PHP/.Net) or you can use SQLLite.
Not found any method for direct connectivity with the database using JDBC.
If any one found direct connecivity withe database using JAVA then please reply.
Thanks -
Hello,
I'll like some advice on the topic mentioned above. I'm a beginner of java programming and have elementry knowledge about java. I'll like to know how is it possible to input the list of data in Excel format into Java Database Connectivity and how am I able to extract out the info. that I'll need. Like say the columns/field on designation and name. How am I able to extract the data and change it like to delete or edit the info.??
Pls. explain it step-by-step your patience is really appreciated. Thanks and God Bless.You should search Javaworld for "Excel" - they've had a few articles about using JDBC to access Excel. As far as I recall, though, you can't alter data in Excel through JDBC, only read it.
http://www.javaworld.com
There are other ways of getting at Excel data through Java but they're not very good either (unless you want to use a Java-COM bridge). -
How to access database connection from datatsource in a standalone java ap
My java standalone application wants connection to database with lookup to datasource name which is configured in the oc4j app server.
Please guide me with some ideas to acheieve this.user510497,
Following sample program requires access to classes in "oc4j.jar" file.
Test environment:
* Server:
+ OC4J stand-alone 10.1.2.0.2
+ Red Hat Enterprise Linux AS release 3
+ Java HotSpot(TM) Client VM (build 1.4.2_08-b03, mixed mode)
+ Oracle Database 10g Release 10.1.0.4.0 - 64bit Production
* Client
+ Microsoft Windows XP Professional Version 2002 Service Pack 2
+ Java HotSpot(TM) Client VM (build 1.5.0_08-b03, mixed mode, sharing)
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DataSrc2 {
public static void main(String[] args) {
Connection conn = null;
Properties l_props = new Properties();
l_props.put(Context.INITIAL_CONTEXT_FACTORY,
"com.evermind.server.rmi.RMIInitialContextFactory");
l_props.put(Context.PROVIDER_URL, "ormi://your_OC4J_host/");
l_props.put(Context.SECURITY_PRINCIPAL, "your_OC4J_user");
l_props.put(Context.SECURITY_CREDENTIALS, "your_OC4J_password");
Context l_jndiContext = null;
try {
l_jndiContext = new InitialContext(l_props);
Object l_obj = l_jndiContext.lookup("default-data-source");
DataSource ds = (DataSource) l_obj;
conn = ds.getConnection("scott","tiger");
DatabaseMetaData dbmd = conn.getMetaData();
System.out.println(dbmd.getDatabaseProductVersion());
catch (NamingException x_naming) {
x_naming.printStackTrace();
catch (SQLException xSql) {
xSql.printStackTrace();
finally {
if (l_jndiContext != null) {
try {
l_jndiContext.close();
catch (NamingException x_naming) {
System.err.println("Failed to close JNDI context.");
x_naming.printStackTrace();
if (conn != null) {
try {
conn.close();
catch (SQLException xSql) {
System.err.println("Failed to close [database] connection.");
xSql.printStackTrace();
}NOTES:
1. Datasource lookup name is value of "default-data-source" attribute of "orion-application" element in file:
<OC4J_HOME>/j2ee/home/config/application.xmlGood Luck,
Avi. -
How to use Forms Default Database Connection in java class
When a form based application is started, a connection is made with underlying database. This is the Default (Primay) Database Connection.
The problem is I have some of my business logic implemented in a java class. In this class I have to make a another connection with the same database. What I want to do is to use the original Database Connection in the java class. In this I may avoid the overhead of reconnection.
Could anyone pls guide me in this way...you can't share the forms connection. Sorry :(
-
How to get total number of Database connections from Java code
Hi,
I am using Myql4.1.12.
I am conncting to mysql through Java.
I want to know how many active database connections were running at a specific time. Is it possible?
Can you please help me.
Thanks in advance.Seems like this would be a question for MySql, not for Java. And if it's possible you'd run some MySql utility to do that, not code it in a Java app.
-
Can i use single database connection in a hole java application?
can i use single database connection in a hole java application?.I have so many forms to use database connection.
Theoretically you can. Not only theoretically. I've seen lots of application which only uses one database connection (they were using, oracle or mysql)
The first reply given here assumed that the answer to
your question depends only on the design of your
application. That is not true.Yes it's true. Nothing in the original questions says that you aren't allowed to open or close the single connection that you have. It's looks more like the OP is interested in sharing a connection (i.e having a singleton or a connection pool with only one connection)
It does also depend on the behaviour of the database
in the background.
Most databases have a time out for connections that
are idle Not a problem. Most implementations of connection pools and applications which keeps a connection open have a timer which calls e.g. select * from dual (if you are using oracle) when the connection has been idle for X minutes.
(some, like db2 on z/OS, even cancel
connections, that are not idle, if they are open a
certain amount of time or have reached a given limit
of cpu seconds.)You would also have that problem if you had a connection pool with several connections.
In essence: If you have no control over the time
your application runs (and therefore your connection
is open) or over type or the configuration of the
database you are accessing, you can't do it.See above.
The closest thing to what you want would be using
PooledConnections, iif those are supported for the
database you want to access.Not true.
Kaj -
How to get database connection in common java class
hi friendz,
plz help me...
I am using JDEV 11.1.2.2.0 version.
my problem is I'm writing common java class which can reuse any application.
in this case when im create database connection like this,
String username = "a";
String password = "b";
String thinConn = "jdbc:oracle:thin:@IP:1521:database";
DriverManager.registerDriver(new OracleDriver());
Connection conn =
DriverManager.getConnection(thinConn, username, password);
conn.setAutoCommit(false);
return conn;
but this statement not working in java class.its working only backing bean.
import oracle.jdbc.OracleDriver;
DriverManager.registerDriver(new OracleDriver());
how can i do that??
hope your help
-Harsh-What is the error message in Java class?
With JDBC 4.0 driver the DriverManager class has added support for the Java SE Service Provider mechanism to the getConnection() and getDrivers() methods using which JDBC drivers may be loaded automatically. The following Class.forName() method is not required to be invoked.
Class.forName(“oracle.jdbc.OracleDriver”);
Only the following is required to obtain a connection.
String url="jdbc:oracle:thin:@localhost:1521:ORCL";
Connection connection = DriverManager.getConnection(url,"oe", "pw");
Maybe you are looking for
-
The Image viewer flash element could not be found
The image viewer flash element could not be found. What should I do? Any plug in exists or is it mistake in program? Help me, please. Thx Joe
-
Spotify on Nokia 2730 ever possible?
Will it ever be possible on my Nokia 2730? Or do I need to get an iphone? What is stopping it, limitations in the phone, OS, hardware? Or some implementation needed to be done to the spotify software? For those who have never heard of it, Spotify is
-
GOA + Local Contract distribution to R/3 in Extended Classic Scenario
Dear SRM Gurus, System Information: SRM Server 5.5 EBP5.5 Technical Scenario: Extended Classic Scenario. Q1) We have created a Global Outline Agreement in EBP. We want this to be distributed to R/3. But when we click on distribute, it does not get
-
Re: GTX 780 reaching 100% usage causes game to crash?
Well I have been busy researching my problem online, trying different driver versions. I changed my PCIe to G1 in bios and switched to the 344.75 driver, so far so good. I am now running @ 1178mhz core / 3348 memory. I am thinking that it was a drive
-
Not enough memory space for clips recorded (transfer from DV to imovie)
Hi. This is one question that I have always wanted to ask, but since I hard edit a long video clips, so I have been procrastinating to ask this question. Recently, been asked to film a childcare performance for a friend. estimated amount of clips I w