JDBC连接数据库--入门

本实例使用的是MS SQL Server 2000.它的功能是从pubs数据库里的titles表中读取所有著作的title(标题)和price(价格),并在控制台显示出来!

  
  
  
  
  1. import java.sql.Connection;  
  2. import java.sql.DriverManager;  
  3. import java.sql.ResultSet;  
  4. import java.sql.Statement;  
  5.  
  6. public class SimpleJDBCTest {  
  7.  
  8. public static final String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";  
  9.  
  10. public static final String drivername = "com.microsoft.jdbc.sqlserver.SQLServerDriver";  
  11.  
  12. public static final String user = "sa";  
  13.  
  14. public static final String password = "sa";  
  15.  
  16. public static void main(String[] args) {  
  17. String sql = "select title,price from titles";  
  18. Connection connection = null;  
  19. Statement statement = null;  
  20. ResultSet resultSet = null;  
  21. try {  
  22. Class.forName(drivername);  
  23. System.out.println("加载驱动成功!");  
  24. connection = DriverManager.getConnection(url, userpassword);  
  25. System.out.println("连接数据库成功!");  
  26. statement = connection.createStatement();  
  27. resultSet = statement.executeQuery(sql);  
  28. while (resultSet.next()) {  
  29. System.out.println("书名:" + resultSet.getString("title") + "定价:" 
  30. + resultSet.getDouble("price"));  
  31. }  
  32. resultSet.close();  
  33. statement.close();  
  34. connection.close();  
  35.  
  36. } catch (Exception e) {  
  37. e.printStackTrace(System.out);  
  38. } finally {  
  39. try {  
  40. if (resultSet != null) {  
  41. resultSet.close();  
  42. }  
  43. } catch (Exception e) {  
  44. System.err.println("关闭ResultSet时发生异常!");  
  45. }  
  46. try {  
  47. if (statement != null) {  
  48. statement.close();  
  49. }  
  50. } catch (Exception e) {  
  51. System.err.println("关闭statement时发生异常!");  
  52. }  
  53. try {  
  54. if (connection != null) {  
  55. connection.close();  
  56. }  
  57. } catch (Exception e) {  
  58. System.err.println("关闭connection时发生异常!");  
  59. }  
  60. }  
  61. }  

 

你可能感兴趣的:(jdbc,入门,连接数据库)