日期:2014-05-16 浏览次数:20573 次
本实例实现了Java与SQL Server 2000数据库的连接,以数据库pubs为例!
?
/* JdbcDriver.java*/
package learner; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JdbcDriver { private String className;//驱动名 private String url;//数据库连接url private String dbName;//要访问的数据库 private String username;//数据库的登录名 private String password;//数据库的登录密码 private Connection conn; private Statement stmt; private ResultSet rs; public JdbcDriver() { dbName = "pubs"; username = "pubs"; password = "pubs"; className = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; url = "jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=" + dbName; try { Class.forName(className); try { conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } try { stmt = conn.createStatement(); rs = stmt.executeQuery("select * from authors"); } catch (SQLException e) { e.printStackTrace(); } try { while (rs.next()) { System.out.println(rs.getString(1)); } } catch (SQLException e1) { e1.printStackTrace(); } try { rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) { new JdbcDriver(); } }
?
?