java编程过程中,连接常用数据库的方法,包括sql server,Access,mysql。
1. 用jdbc连接sql server2000.
a.使用jtds-1.2.5.jar的驱动程序进行连接:
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
System.out.println("加载失败");
}
try
{
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/test", "sa", "nihao");
}
catch(SQLException e)
{
System.out.println("连接失败" + e.getMessage());
}
b.使用microsoft提供的驱动程序进行连接,它需要的包有:msbase.jar,mssqlserver.jar,msutil.jar:
try
{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
}
catch(ClassNotFoundException e)
{
System.out.println("加载失败");
}
try
{
conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test", "sa", "nihao");
}
catch(SQLException e)
{
System.out.println("连接失败" + e.getMessage());
}
2.用jdbc连接mysql:
需要用到的jar包是:
String mySQLDriver="org.gjt.mm.mysql.Driver";
String url="jdbc:mysql://localhost:3306";
try
{
Class.forName(mySQLDriver);
conn=DriverManager.getConnection(url+"/"+database, user, password);
stmt=conn.createStatement();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException e)
{
e.printStackTrace();
}
3.使用jdbc-odbc连接Access数据库:
String filePath="db/myDB.mdb";
String url="jdbc:odbc:Driver= {Microsoft Access Driver (*.mdb)};DBQ=";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection(url+filePath,"","");
stmt=con.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch(SQLException e)
{
e.printStackTrace();
}
4.jndi连接
try {
Context initCtx=new InitialContext();
Context envCtx=(Context)initCtx.lookup("java:comp/env");
DataSource ds=(DataSource)envCtx.lookup("jdbc/s3DS");
if(ds!=null)
{
conn=ds.getConnection();
}
else
{
System.out.println("datasource initial fail");
}
} catch (NamingException e) {
// TODO Auto-generated catch block
System.out.println("datasource initial error");
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Connection initial error");
e.printStackTrace();
}
META-INF下建立一个context.xml
WEB-INF/web.xml
type="javax.sql.DataSource" username="root" password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mSynchronized?useUnicode=true&characterEncoding=utf-8"
maxActive="10"
/>
web.xml中添加
S3 datasource
jdbc/s3DS
javax.sql.DataSource
Container