JDBC访问数据库源代码
(2010-11-16 08:04:37)
有两种方式,第一种方式(直连方式)如下:
import java.sql.*;
class AccessDataBase
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D://db1.mdb";
Connection conn;
conn=DriverManager.getConnection(url,"","");
Statement stament=conn.createStatement();
ResultSet rs=stament.executeQuery("select * from userinfo");
while(rs.next())
{
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
System.out.println();
}
stament.close();
conn.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
第二种方式(需要首先设置DSN)如下:
import java.sql.*;
class AccessDataBase
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:usertable";
Connection conn;
conn=DriverManager.getConnection(url,"dgd","admin");
Statement stament=conn.createStatement();
ResultSet rs=stament.executeQuery("select * from userinfo");
while(rs.next())
{
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
System.out.println();
}
stament.close();
conn.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}