日常的时候,经常有同学问有关如何连接到数据库的问题,现在写下来,希望对有的人,有些帮助。
1. 加载一个对应数据库的jdbc驱动
在建立到一个数据库的连接之前,必须先加载这个数据库的jdbc驱动程序,加载之后此driver会自动注册到jdbc驱动列表中。加载一个jdbc驱动有两种方法。
a) 在命令行方式下指定驱动器或者用冒号分割驱动器列表:
具体命令如下:
c:/>java ?cdjdbc.drivers = com.company1.driver:com.company2.driver youproject
b)第二种方法,在程序中调用class.forname()方法。推荐使用。。。。
try
{
string drivername = “com.imaginary.sql.msql.msqldriver”;
class.forname(drivername).newinstance();
}
catch(classnotfoundexception e1)
{
//catch could not find database driver exception.
}
2.连接到数据库。
根据您后台待连接的数据库不同,而有小小的差别。
a) 连接到oracle数据库。
connection connection = null ;
try
{
//load the jdbc driver ;
string drivername = “oracle.jdbc.driver.oracledriver”;
class.forname(drivername).newinstance();
//create a connection to the database;
string servername = “127.0.0.1”;
string serverport = “1521”;
string serverid = “datebase1”
string username = “hello”;
string userpsw = “world”;
string url = “jdbc:oracle.thin:@” + servername + “:” + serverport + “:” + serverid ;
connection = drivermanager.getconnection(url , username , userpsw);
}
catch(classnotfoundexception e1)
{
//catch could not find database driver exception.
}
catch(sqlexception e2)
{
//catch could not connect to the database exception.
}
b) 连接到一个sql server数据库。
connection connection = null ;
try
{
//load the jdbc driver ;
string drivername = “com.microsoft.jdbc.sqlserver.sqlserverdriver”;
class.forname(drivername).newinstance();
//create a connection to the database;
string servername = “127.0.0.1”;
string serverport = “1433”;
string serverid = servername + serverport ;
string username = “hello”;
string userpsw = “world”;
string url = “jdbc:jsqlconnect ://” + serverid ;
connection = drivermanager.getconnection(url , username , userpsw);
}
catch(classnotfoundexception e1)
{
//catch could not find database driver exception.
}
catch(sqlexception e2)
{
//catch could not connect to the database exception.
}
c) 连接到一个mysql数据库上。。。。
connection connection = null ;
try
{
//load the jdbc driver ;
string drivername = “org.gjt.mm.mysql.driver”;
class.forname(drivername).newinstance();
//create a connection to the database;
string servername = “127.0.0.1”;
string serverid = “database”;
string username = “hello”;
string userpsw = “world”;
string url = “jdbc:mysql ://” + servername + “/” + serverid ;
connection = drivermanager.getconnection(url , username , userpsw);
}
catch(classnotfoundexception e1)
{
//catch could not find database driver exception.
}
catch(sqlexception e2)
{
//catch could not connect to the database exception.
}
综合上面的三种数据库连接方式 , 其实大同小异。由于访问不同的数据库和所使用的数据库驱动程序不同,所以导致代码表面上有小小不同,但透过表面看来,内部都是
1. 加载一个特定的数据库jdbc驱动。
2. 连接到一个数据库。
3. 之后,就可以对一个特定的数据库进行特定的操作了。
闽公网安备 35060202000074号