java 链接jdbc
时间:2021-07-01 10:21:17
帮助过:2人阅读
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
标签: