2.在没有Jdbc驱动的情况下可以使用Odbc驱动,以jdbc-odbc bridge的方式访问。
3.通过mysql的jdbc驱动访问mysql:
1).下载mysql的jdbc驱动放到jre1.5.0_13\lib\ext目录下(不是jdk1.5.0_13\lib\ext目录,这点与其它资料说的不同,不知是新版本改了还是我机器的配置问题)
2).代码如下:
String mysqlDriver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/mysql";
String username = "root";
String password = "root";
try {
Class.forName(mysqlDriver);
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select host, user from User");
while(rs.next())
{
System.out.print(rs.getString("host"));
System.out.print(rs.getString("user"));
System.out.println();
}
rs.close();
connection.close();
}
catch (ClassNotFoundException e) {
System.out.println("ClassNotFound:" + e.getMessage());
}
catch (SQLException e) {
System.out.println("SQLException:" + e.getMessage());
}
4.通过SqlServer的odbc驱动访问SqlServer:
1).在ODBC管理器中建一个ODBC DSN为pubs,连接到SqlServer的pubs数据库
2).代码如下:
String odbcDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:pubs";
String username = "sa";
String password = "sa";
try {
Class.forName(odbcDriver);
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select au_id,au_lname from Authors");
while (rs.next()) {
System.out.print(rs.getString("au_id"));
System.out.print(rs.getString("au_lname"));
System.out.println();
}
rs.close();
connection.close();
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFound:" + e.getMessage());
} catch (SQLException e) {
System.out.println("SQLException:" + e.getMessage());
}