JAVA连接常用数据库的方法总结
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<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/s3DS" auth="Container"
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"
/>
</Context>web.xml中添加
<resource-ref>
<description>S3 datasource</description>
<res-ref-name>jdbc/s3DS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>