今天学习的内容是:JDBC
通常jdbc连接分6步:
1)注册驱动;
2)建立连接;
3)创建Statement;
4)执行sql 语句;
5)处理结果集(若sql 语句为查询语句);
6)关闭连接。
代码示例:
1 public void testJdbc(){
2 Connection con = null;
3 PreparedStatement ps = null;
4 ResultSet rs = null;
5 try{
6 //step1:注册驱动;
7 Class.forName("oracle.jdbc.driver.OracleDriver");
8 //step 2:获取数据库连接;
9 con=DriverManager.getConnection(
10 "jdbc:oracle:thin:@192.168.0.39:1521:TARENADB",
11 "sd0605","sd0605");
12 /************************查询************************/
13 //step 3:创建Statement;
14 String sql = "SELECT id, fname, lname, age, FROM
15 Person_Tbl";
16 ps = con.prepareStatement(sql);
17 //step 4 :执行查询语句,获取结果集;
18 rs = ps.executeQuery();
19 //step 5:处理结果集—输出结果集中保存的查询结果;
20 while (rs.next()){
21 System.out.print("id = " + rs.getLong("id"));
22 System.out.print(" , fname = " +
23 第35 页共59 页
24 rs.getString("fname"));
25 System.out.print(" , lname = " +
26 rs.getString("lname"));
27 System.out.print(" , age = " + rs.getInt("age"));
28 }
29 /************************JDBC 修改*********************/
30 sql = "UPDATE Person_Tbl SET age=23 WHERE id = ?";
31 ps = con.prepareStatement(sql);
32 ps.setLong(1, 88);
33 int rows = ps.executeUpdate();
34 System.out.println(rows + " rows affected.");
35 } catch (Exception e){
36 e.printStackTrace();
37 } finally{
38 try{
39 con.close(); //关闭数据库连接,以释放资源。
40 } catch (Exception e1) {
41 }
42 }
43 }
下面搬运:http://www.cnblogs.com/centor/p/6142775.html
以mysql为例
工具:eclipse
MySQL5.6
MySQL连接驱动:mysql-connector-java-5.1.27.jar
加载驱动:
1. 在工程目录中创建lib文件夹,将下载好的JDBC放到该文件夹下,如下图所示:
2. 右键工程名,在java build path中的Libraries分页中选择Add JARs...,选择刚才添加的JDBC,如下图:
数据包准备:
在数据库sqltestdb中创建如下数据表emp:
1
2
3
4
5
6
7
|
CREATE
TABLE
emp(
empno
INT
(4)
PRIMARY
KEY
,
ename
VARCHAR
(10),
job
VARCHAR
(9),
hiredate
DATE
,
sal
FLOAT
(7,2)
) ;
|
添加数据:
连接数据库并读取数据:
数据库名称:sqltestdb
数据包名称:emp
端口号:3306
用户名:root
密码:root
1 package sqldemo;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7 import java.sql.Statement;
8
9 public class main {
10
11 public static void main(String[] args) {
12 //声明Connection对象
13 Connection con;
14 //驱动程序名
15 String driver = "com.mysql.jdbc.Driver";
16 //URL指向要访问的数据库名mydata
17 String url = "jdbc:mysql://localhost:3306/sqltestdb";
18 //MySQL配置时的用户名
19 String user = "root";
20 //MySQL配置时的密码
21 String password = "123456";
22 //遍历查询结果集
23 try {
24 //加载驱动程序
25 Class.forName(driver);
26 //1.getConnection()方法,连接MySQL数据库!!
27 con = DriverManager.getConnection(url,user,password);
28 if(!con.isClosed())
29 System.out.println("Succeeded connecting to the Database!");
30 //2.创建statement类对象,用来执行SQL语句!!
31 Statement statement = con.createStatement();
32 //要执行的SQL语句
33 String sql = "select * from emp";
34 //3.ResultSet类,用来存放获取的结果集!!
35 ResultSet rs = statement.executeQuery(sql);
36 System.out.println("-----------------");
37 System.out.println("执行结果如下所示:");
38 System.out.println("-----------------");
39 System.out.println("姓名" + "\t" + "职称");
40 System.out.println("-----------------");
41
42 String job = null;
43 String id = null;
44 while(rs.next()){
45 //获取stuname这列数据
46 job = rs.getString("job");
47 //获取stuid这列数据
48 id = rs.getString("ename");
49
50 //输出结果
51 System.out.println(id + "\t" + job);
52 }
53 rs.close();
54 con.close();
55 } catch(ClassNotFoundException e) {
56 //数据库驱动类异常处理
57 System.out.println("Sorry,can`t find the Driver!");
58 e.printStackTrace();
59 } catch(SQLException e) {
60 //数据库连接失败异常处理
61 e.printStackTrace();
62 }catch (Exception e) {
63 // TODO: handle exception
64 e.printStackTrace();
65 }finally{
66 System.out.println("数据库数据成功获取!!");
67 }
68 }
69
70 }
运行结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
Succeeded connecting
to
the
Database
!
-----------------
执行结果如下所示:
-----------------
姓名 职称
-----------------
李兴华 经理
张三 总监
王五 厂长
齐秦 书记
张刚 组长
曹操 财务
李四 总裁
数据库数据成功获取!!
|
增加、删除和修改数据:
增加数据:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
String name;
String id;
PreparedStatement psql;
ResultSet res;
//预处理添加数据,其中有两个参数--“?”
psql = con.prepareStatement(
"insert into emp (empno,ename,job,hiredate,sal) "
+
"values(?,?,?,?,?)"
);
psql.setInt(
1
,
3212
);
//设置参数1,创建id为3212的数据
psql.setString(
2
,
"王刚"
);
//设置参数2,name 为王刚
psql.setString(
3
,
"总裁"
);
DateFormat dateFormat2 =
new
SimpleDateFormat(
"yyyy-MM-dd"
);
Date myDate2 = dateFormat2.parse(
"2010-09-13"
);
psql.setDate(
4
,
new
java.sql.Date(myDate2.getTime()));
psql.setFloat(
5
, (
float
)
2000.3
);
psql.executeUpdate();
//执行更新
|
运行结果:
更新数据:
1
2
3
4
5
6
|
PreparedStatement psql;
//预处理更新(修改)数据,将王刚的sal改为5000.0
psql = con.prepareStatement(
"update emp set sal = ? where ename = ?"
);
psql.setFloat(
1
,(
float
)
5000.0
);
psql.setString(
2
,
"王刚"
);
psql.executeUpdate();
|
更改结果:
删除数据:
1
2
3
4
5
6
|
PreparedStatement psql;
//预处理删除数据
psql = con.prepareStatement(
"delete from emp where sal > ?"
);
psql.setFloat(
1
,
4500
);
psql.executeUpdate();
psql.close();
|
删除结果:
------------------------------------------------------------------------------------------------
这个例子可以说很经典了,还在上学的时候,老师讲jdbc连接就用的类似的方法(怀念QAQ)
不过在项目中,这些东西通常是配在xml或是properties文件里多一点,就像这样
----------------------------------------------------------------------------------------------------
接下来我找一个连接池的例子,相当于写了一个共通类,别的class各种调用这里的方法,也还算方便
这是我之前做毕业设计那会费了好大劲凑出来的,不知道正不正宗,反正是能跑起来!
1 public class BaseDao {
2 // list连接池
3 static ArrayList<Connection> list = new ArrayList<Connection>();
4 /**
5 * 从连接池中获得一个连接
6 */
7 public synchronized static Connection getConnection() throws Exception{
8 Connection con = null;
9 // 如果连接池有连接
10 if (list.size() > 0) {
11 return list.remove(0);
12 }
13 // 连接池中没有连接
14 else {
15 Properties p = new Properties();
16 //加载配置文件
17 p.load(BaseDao.class.getClassLoader().getResourceAsStream("dao/jdbc.properties"));
18 String driverClass = p.getProperty("jdbc.driverClass");
19 String jdbcUrl = p.getProperty("jdbc.jdbcUrl");
20 String username = p.getProperty("jdbc.username");
21 String password = p.getProperty("jdbc.password");
22 //加载驱动
23 Class.forName(driverClass);
24 // 和指定的数据库建立连接
25 for (int i = 0; i < 10; i++) {
26 con = DriverManager.getConnection(jdbcUrl, username,password);
27 list.add(con);
28 }
29 }
30 return list.remove(0);
31 }
32 /**
33 * 关闭结果集
34 * @param rs代表结果集
35 */
36 public static void close(ResultSet rs) throws Exception{
37 if (rs != null)
38 rs.close();
39 }
40 /**
41 * 关闭预处理对象
42 * @param pst代表预处理
43 */
44 public static void close(PreparedStatement pst) throws Exception{
45 if (pst != null)
46 pst.close();
47 }
48 /**
49 * 关闭连接对象
50 * @param con代表连接对象
51 */
52 public synchronized static void close(Connection con) {
53 if (con != null)
54 list.add(con);
55 }
56 /**
57 * 关闭结果集,预处理,连接等对象
58 * @param rs 结果集
59 * @param ps 预处理
60 * @param con 连接
61 */
62 public static void close(ResultSet rs, PreparedStatement ps, Connection con) throws Exception{
63 close(rs);
64 close(ps);
65 close(con);
66 }
67 /**
68 * 根据SQL语句,进行insert,update,delete等操作
69 * @param sql
70 * @param param代表SQL语句里面的通配符(?)对应的值,一定注意顺序
71 * @return
72 */
73 public boolean updateByParams(String sql, Object param[]) throws Exception{
74 boolean flag = false;
75 Connection con = getConnection();
76 PreparedStatement ps = null;
77 ps = con.prepareStatement(sql);
78 //替换参数?
79 if(param != null){
80 for(int i = 1; i <= param.length; i++){
81 ps.setObject(i, param[i-1]);
82 }
83 }
84 int n = ps.executeUpdate();
85 if(n > 0)
86 flag = true;
87 close(null, ps, con);
88 return flag;
89 }
90 /**
91 * 批量进行insert,update,delete等操作
92 * @param sql
93 * @param param
94 * @return
95 */
96 public boolean BatchUpdateByParams(String sql, Object param[][]) throws Exception{
97 Connection con = getConnection();
98 PreparedStatement ps = null;
99 ps = con.prepareStatement(sql);
100 //替换参数?
101 if(param != null){
102 for(int i = 0; i < param.length; i++){
103 for(int j = 1; j <= param[i].length; j++){
104 ps.setObject(j, param[i][j-1]);
105 }
106 ps.addBatch();
107 }
108 ps.executeBatch();
109 }
110 close(null, ps, con);
111 return true;
112 }
113 /**
114 * 查询操作
115 * @param sql
116 * @param param
117 * @return List<Map<String, Object>>,map的key是查询的列名(小写)或别名,map的value是每列对应的值
118 */
119 public static List<Map<String, Object>> select(String sql,Object[] param) throws Exception{
120 Connection con = getConnection();
121 PreparedStatement ps = null;
122 ResultSet rs = null;
123 List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
124 ps = con.prepareStatement(sql);
125 //替换参数?
126 if(param != null){
127 for(int i = 1; i <= param.length; i++){
128 ps.setObject(i, param[i-1]);
129 }
130 }
131 rs = ps.executeQuery();//执行查询
132 ResultSetMetaData rm = rs.getMetaData();
133 //获得结果集列的总数
134 int count = rm.getColumnCount();
135 while(rs.next()){
136 Map<String,Object> map = new HashMap<String, Object>();
137 for(int i = 1; i <= count; i++){
138 //key是列名,并且是小写的;value是根据列名获得某条记录对应的值
139 map.put(rm.getColumnName(i).toLowerCase(), rs.getObject(rm.getColumnName(i)));
140 }
141 list.add(map);
142 }
143 close(rs, ps, con);
144 return list;
145 }
146 /**
147 * 获得一个以时间字符串为标准的ID,固定长度是17位
148 * @return
149 */
150 public static String getStringID(){
151 String id=null;
152 Date date=new Date();
153 SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS");
154 id=sdf.format(date);
155 return id;
156 }
157 }
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
发现孤傲苍狼大神也发表过关于连接池的随笔,写的很容易理解,下面是传送门,我已经认真读一遍了,你呢?
哎,我何时能和他一样什么都会。。。。。。o(╥﹏╥)o
https://www.cnblogs.com/xdp-gacl/p/4002804.html
然后!今天工作过程中出现了有关js jsonp的错误,因为快下班了就随便查了下,感觉这部分挺有意思,那么!明晚就决定写这个了!
以上就是我今日份的jdbc学习内容,我们下期再见!
来源:oschina
链接:https://my.oschina.net/u/4257455/blog/3829816