码迷,mamicode.com
首页 > 数据库 > 详细

java 链接jdbc

时间:2016-01-27 17:01:42      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

 

 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 import java.util.ResourceBundle;
 7 
 8 public class ConnnectionUtils {
 9 
10     private static String dbDriver = ""; //com.mysql.jdbc.Driver
11     private static String url = "";      //jdbc\:mysql\://localhost\:3306/dabasename?useUnicode\=true&characterEncoding\=UTF-8
12     private static String user = "";     //username
13     private static String passw = "";    //password
14     
15     static Connection conn=null;
16     
17     static {
18         
19         ResourceBundle source = ResourceBundle.getBundle("config");  //config.properties
20         dbDriver = source.getString("driverClassName");
21         url = source.getString("jdbc_url");
22         user = source.getString("jdbc_username");
23         passw = source.getString("jdbc_password");
24     }
25     
26     public static Connection getConnection(){
27         try {
28             // 加载驱动
29             Class.forName(dbDriver);
30             // 获取链接
31             conn = DriverManager.getConnection(url,user,passw);
32         } catch (Exception e) {
33             e.printStackTrace();
34         }
35         
36         return conn;
37     }
38     
39     //使用后关闭链接
40     public static void  close(){
41         if (conn != null) {
42             try {
43                 conn.close();
44             } catch (SQLException e) {
45                 e.printStackTrace();
46             }
47         }
48     }
49     
50     
51     
52     
53     public static void main(String[] args) {
54         Connection conn = ConnnectionUtils.getConnection();
55         System.out.println(conn);
56         String sql = "select * from tableName";
57         
58         try {
59             // 执行SQL  
60             Statement statement = conn.createStatement();
61             // 获得结果集 
62             ResultSet result = statement.executeQuery(sql);
63             
64             //如果有结果集 ,对结果进行处理
65             while (result.next()) {
66                 String app_url = result.getString("oneStringColumnName");
67                 System.out.println(app_url);
68                 
69             }
70             //关闭链接
71             ConnnectionUtils.close();
72         } catch (SQLException e) {
73             e.printStackTrace();
74         }
75         
76     }
77 }

 

QQ:871820604

java 链接jdbc

标签:

原文地址:http://www.cnblogs.com/hjwbla/p/5163781.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!