使用JDBC连接数据库

JDBC(Java Data Base Connectivity)数据库连接,我们在编写web应用或java应用程序要连接数据库时就要使用JDBC。使用JDBC连接数据库一般步骤有:

1、加载驱动程序 Class.forName(driver);

2、创建连接对象 Connection con = DriverManager.getConnection(url,username,password);

3、创建sql语句执行对象 

4、执行sql语句

5、对执行结果进行处理

6、关闭相关的连接对象(顺序跟声明的顺序相反)

下面是以建立与MySQL数据库连接的例子,其他数据库的过程类似

 

 1 import java.sql.Connection;
 2 import java.sql.DriverManager;
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 import java.sql.Statement;
 6 
 7 public class DBConnection
 8 {
 9 
10     public static void main(String[] args)
11     {
12         String driver = "com.mysql.jdbc.Driver";
13 
14         //localhost指本机,也可以用本地ip地址代替,3306为MySQL数据库的默认端口号,“user”为要连接的数据库名
15         String url = "jdbc:mysql://localhost:3306/user";
16 
17         //填入数据库的用户名跟密码
18         String username = "test";
19         String password = "test";
20         String sql = "select * from user";//编写要执行的sql语句,此处为从user表中查询所有用户的信息
21 
22         try
23         {
24             Class.forName(driver);//加载驱动程序,此处运用隐式注册驱动程序的方法
25 
26         }
27         catch(ClassNotFoundException e)
28         {
29             e.printStackTrace();
30         }
31         try
32         {
33             Connection con = DriverManager.getConnection(url,username,password);//创建连接对象
34             Statement st = con.createStatement();//创建sql执行对象
35             ResultSet rs = st.executeQuery(sql);//执行sql语句并返回结果集
36 
37             while(rs.next())//对结果集进行遍历输出
38             {
39 
40                 System.out.println("username: "+rs.getString(1));//通过列的标号来获得数据
41                 System.out.println("useradd: "+rs.getString("useradd"));//通过列名来获得数据
42                 System.out.println("userage: "+rs.getInt("userage"));
43             }
44             //关闭相关的对象
45             if(rs != null)
46             {
47                 try
48                 {
49                     rs.close();
50                 }
51                 catch(SQLException e)
52                 {
53                     e.printStackTrace();
54                 }
55             }
56 
57             if(st != null)
58             {
59                 try
60                 {
61                     st.close();
62                 }
63                 catch(SQLException e)
64                 {
65 
66                     e.printStackTrace();
67                 }
68             }
69 
70             if(con !=null)
71             {
72 
73                 try
74                 {
75 
76                     con.close();
77                 }
78                 catch(SQLException e)
79                 {
80                     e.printStackTrace();
81                 }
82             }
83         }
84         catch(SQLException e)
85         {
86             e.printStackTrace();
87         }
88     }
89 }

 

posted @ 2014-08-24 11:22  CIACs  阅读(407)  评论(0编辑  收藏  举报