[关闭]
@MRsunhuimin 2019-08-12T14:16:55.000000Z 字数 9130 阅读 188

JDBC连接(08.12)

web

作者:孙慧敏

1. jdbc连接数据库步骤

准备jar
mysql-connector-java-5.1.0-bin.jar

  • 加载驱动Class.forName("com.mysql.jdbc.Driver");
  • 使用DriverManager获取数据库connection连接
  • 创建Statement对象 用于执行SQL语句
  • 执行SQL语句
  • 释放资源
  1. //jdbc连接数据库,使用Statement接口
  2. package com.hz.test;
  3. import java.sql.*;
  4. public class Test1 {
  5. public static void main(String[] args) {
  6. Connection conn = null;
  7. Statement stmt = null;
  8. ResultSet rs = null;
  9. try {
  10. //加载驱动 方言
  11. Class.forName("com.mysql.jdbc.Driver");
  12. //准备数据库连接路径
  13. String url = "jdbc:mysql://192.168.0.157:3306/xxshop";
  14. //用户名与密码
  15. String username = "root";
  16. String userpwd = "root";
  17. //根据路径,用户名,密码 使用DriverManager获取数据库connection连接
  18. conn =DriverManager.getConnection(url,username,userpwd);
  19. //准备要执行的SQL语句
  20. String sql = "SELECT user_id,user_name FROM sf_user";
  21. //创建Statement对象 用于执行SQL语句
  22. stmt = conn.createStatement();
  23. //执行SQL语句
  24. rs =stmt.executeQuery(sql);
  25. //处理ResultSet结果集
  26. //rs.next() 返回boolean 值
  27. while (rs.next()){
  28. //long id = rs.getLong(1);
  29. //String name = rs.getString(2);
  30. long id = rs.getLong("user_id");
  31. String name = rs.getString("user_name");
  32. System.out.println("用户id:"+id+"用户名:"+name);
  33. }
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }finally {
  37. try {
  38. //释放资源
  39. rs.close();
  40. stmt.close();
  41. conn.close();
  42. } catch (SQLException e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. }
  47. }

2. 三种数据库驱动

com.microsoft.jdbc.sqlserver.SQLServerDriver(SQL Server) 

com.mysql.jdbc.Driver(MySql) 

oracle.jdbc.driver.OracleDriver(Oracle)

3. Statement常用对象

    ResultSet executeQuery(sql)
    执行sql查询语句,并返回ResultSet对象

    int executeUpdate(sql)
    执行insert,update,delete语句,返回受影响行数

    boolean execute(sql)
    执行insert,update,delete语句,返回true或false false成功

4. 防止数据库乱码及日期出错

    放入url连接路径之后

    ?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull

5. PreparedStatement对象使用

    防止SQL注入,使用占位符“?”方式进行SQL拼接

6. 练习,使用PreparedStatement进行增删改查等

  1. package com.hz.test;
  2. import com.hz.entity.Goods;
  3. import com.hz.entity.User;
  4. import java.sql.*;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. public class Tset2 {
  8. //验证
  9. public User loginUser(String user_name, String user_password){
  10. Connection conn = null;
  11. PreparedStatement ps = null;
  12. ResultSet rs = null;
  13. try {
  14. Class.forName("com.mysql.jdbc.Driver");//加载驱动 方言
  15. String url = "jdbc:mysql://192.168.0.157:3306" +
  16. "/xxshop?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull";
  17. String username = "root";
  18. String userpwd = "root";
  19. conn = DriverManager.getConnection(url,username,userpwd);//获取Connection对象
  20. String sql = "select user_id,user_name,user_password from sf_user where user_name=? and user_password=?";
  21. ps = conn.prepareStatement(sql);
  22. ps.setString(1,user_name);//第一个占位符处
  23. ps.setString(2,user_password);//ps.setXXXX(位置<从1开始>,值<参数>)
  24. rs = ps.executeQuery();//执行查询
  25. User user = null;//用于判断 等于null登录失败,否则成功
  26. while (rs.next()){
  27. user = new User();//进入循环,登录成功,创建user对象
  28. user.setUser_id(rs.getLong("user_id"));//使用rs.getXXX("返回的列名") 放入user对象
  29. user.setUser_name(rs.getString("user_name"));
  30. user.setUser_password(rs.getString("user_password"));
  31. }
  32. return user;
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. } finally {
  36. try {
  37. ps.close();
  38. conn.close();
  39. } catch (SQLException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. return null;
  44. }
  45. //查询
  46. public void selectUser(){
  47. Connection conn = null;
  48. PreparedStatement ps = null;
  49. ResultSet rs = null;
  50. try {
  51. Class.forName("com.mysql.jdbc.Driver");
  52. String url = "jdbc:mysql://192.168.0.157:3306" +
  53. "/xxshop?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull";
  54. String username = "root";
  55. String userpwd = "root";
  56. conn = DriverManager.getConnection(url,username,userpwd);
  57. String sql = "select user_id,user_name from sf_user";
  58. ps = conn.prepareStatement(sql);
  59. rs = ps.executeQuery();
  60. while (rs.next()){
  61. long id = rs.getLong("user_id");
  62. String name = rs.getString("user_name");
  63. System.out.println("用户ID:"+id+"\t"+"用户名:"+name);
  64. }
  65. } catch (Exception e) {
  66. e.printStackTrace();
  67. } finally {
  68. try {
  69. ps.close();
  70. conn.close();
  71. } catch (SQLException e) {
  72. e.printStackTrace();
  73. }
  74. }
  75. }
  76. //增加
  77. public boolean addUser(){
  78. Connection conn = null;
  79. PreparedStatement ps = null;
  80. boolean i = false;
  81. try {
  82. Class.forName("com.mysql.jdbc.Driver");
  83. String url = "jdbc:mysql://192.168.0.157:3306" +
  84. "/xxshop?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull";
  85. String username = "root";
  86. String userpwd = "root";
  87. conn = DriverManager.getConnection(url,username,userpwd);
  88. String sql = "INSERT INTO sf_user(user_name,user_password) VALUES(?,?)";
  89. ps = conn.prepareStatement(sql);
  90. ps.setString(1,"李四");
  91. ps.setString(2,"qwert");
  92. if (ps.executeUpdate()>0){
  93. i=true;
  94. System.out.println("添加成功");
  95. }else{
  96. System.out.println("添加失败!");
  97. }
  98. } catch (Exception e) {
  99. e.printStackTrace();
  100. } finally {
  101. try {
  102. ps.close();
  103. conn.close();
  104. } catch (SQLException e) {
  105. e.printStackTrace();
  106. }
  107. }
  108. return i;
  109. }
  110. //删除
  111. public boolean deleteUser(){
  112. Connection conn = null;
  113. PreparedStatement ps = null;
  114. boolean i = false;
  115. try {
  116. Class.forName("com.mysql.jdbc.Driver");
  117. String url = "jdbc:mysql://192.168.0.157:3306" +
  118. "/xxshop?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull";
  119. String username = "root";
  120. String userpwd = "root";
  121. conn = DriverManager.getConnection(url,username,userpwd);
  122. String sql = "delete from sf_user where user_id>10";
  123. ps = conn.prepareStatement(sql);
  124. if (ps.executeUpdate()>0){
  125. i=true;
  126. System.out.println("删除成功");
  127. }else{
  128. System.out.println("删除失败!");
  129. }
  130. } catch (Exception e) {
  131. e.printStackTrace();
  132. } finally {
  133. try {
  134. ps.close();
  135. conn.close();
  136. } catch (SQLException e) {
  137. e.printStackTrace();
  138. }
  139. }
  140. return i;
  141. }
  142. //修改
  143. public boolean updateUser(){
  144. Connection conn = null;
  145. PreparedStatement ps = null;
  146. boolean i = false;
  147. try {
  148. Class.forName("com.mysql.jdbc.Driver");
  149. String url = "jdbc:mysql://192.168.0.157:3306" +
  150. "/xxshop?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull";
  151. String username = "root";
  152. String userpwd = "root";
  153. conn = DriverManager.getConnection(url,username,userpwd);
  154. String sql = "update sf_user set user_name='赵六',user_password='123456' where user_id=3";
  155. ps = conn.prepareStatement(sql);
  156. if (ps.executeUpdate()>0){
  157. i=true;
  158. System.out.println("修改成功");
  159. }else{
  160. System.out.println("修改失败!");
  161. }
  162. } catch (Exception e) {
  163. e.printStackTrace();
  164. } finally {
  165. try {
  166. ps.close();
  167. conn.close();
  168. } catch (SQLException e) {
  169. e.printStackTrace();
  170. }
  171. }
  172. return i;
  173. }
  174. //获取所有商品(goods)信息
  175. public List<Goods> getGoodsList(){
  176. Connection conn = null;
  177. PreparedStatement ps = null;
  178. ResultSet rs = null;
  179. try {
  180. Class.forName("com.mysql.jdbc.Driver");
  181. String url = "jdbc:mysql://127.0.0.1:3306" +
  182. "/xxshop?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull";
  183. String username = "root";
  184. String userpwd = "root";
  185. conn = DriverManager.getConnection(url,username,userpwd);
  186. String sql = "SELECT goods_id,goods_title,goods_browse,goods_state FROM sf_goods ";
  187. ps = conn.prepareStatement(sql);
  188. rs = ps.executeQuery();
  189. List<Goods> goodsList = new ArrayList<Goods>();
  190. while (rs.next()){
  191. Goods goods = new Goods();
  192. goods.setGoods_id(rs.getLong("goods_id"));
  193. goods.setGoods_title(rs.getString("goods_title"));
  194. goods.setGoods_browse(rs.getInt("goods_browse"));
  195. goods.setGoods_state(rs.getInt("goods_state"));
  196. goodsList.add(goods);
  197. }
  198. return goodsList;
  199. } catch (Exception e) {
  200. e.printStackTrace();
  201. } finally {
  202. try {
  203. ps.close();
  204. conn.close();
  205. } catch (SQLException e) {
  206. e.printStackTrace();
  207. }
  208. }
  209. return null;
  210. }
  211. //修改商品信息
  212. public int updateGoods(Goods goods){
  213. Connection conn = null;
  214. PreparedStatement ps = null;
  215. try {
  216. Class.forName("com.mysql.jdbc.Driver");
  217. String url = "jdbc:mysql://127.0.0.1:3306" +
  218. "/xxshop?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull";
  219. String username = "root";
  220. String userpwd = "root";
  221. conn = DriverManager.getConnection(url,username,userpwd);
  222. String sql = "UPDATE sf_goods SET goods_title = ?,goods_browse = ?," +
  223. "goods_state = ? WHERE goods_id = ?";
  224. ps = conn.prepareStatement(sql);
  225. ps.setString(1,goods.getGoods_title());
  226. ps.setInt(2,goods.getGoods_browse());
  227. ps.setInt(3,goods.getGoods_state());
  228. ps.setLong(4,goods.getGoods_id());
  229. int i = ps.executeUpdate();
  230. return i;
  231. } catch (Exception e) {
  232. e.printStackTrace();
  233. } finally {
  234. }
  235. return 0;
  236. }
  237. public static void main(String[] args) {
  238. Tset2 t = new Tset2();
  239. // Goods goods = new Goods();
  240. // goods.setGoods_id(2);
  241. // goods.setGoods_title("lalala");
  242. // goods.setGoods_browse(99);
  243. // goods.setGoods_state(100);
  244. // int i = t.updateGoods(goods);
  245. // if (i>0){
  246. // System.out.println("修改成功");
  247. // }else {
  248. // System.out.println("修改失败");
  249. // }
  250. // List<Goods> goodsList = t.getGoodsList();
  251. // for (Goods gd:goodsList){
  252. // System.out.println("商品ID:"+gd.getGoods_id());
  253. // System.out.println("商品标题:"+gd.getGoods_title());
  254. // System.out.println("浏览次数:"+gd.getGoods_browse());
  255. // System.out.println("商品状态(0未上架1在售);"+gd.getGoods_state());
  256. // }
  257. // User user = t.loginUser("张三","111");
  258. // if (user==null) {
  259. // System.out.println("登录失败!");
  260. // } else {
  261. // System.out.println("欢迎"+user.getUser_name()+"登陆成功!");
  262. // }
  263. //t.selectUser();
  264. //t.addUser();
  265. //t.deleteUser();
  266. //t.updateUser();
  267. }
  268. }
  1. //实体类User
  2. package com.hz.entity;
  3. public class User {
  4. private long user_id;
  5. private String user_name;
  6. private String user_password;
  7. public long getUser_id() {
  8. return user_id;
  9. }
  10. public void setUser_id(long user_id) {
  11. this.user_id = user_id;
  12. }
  13. public String getUser_name() {
  14. return user_name;
  15. }
  16. public void setUser_name(String user_name) {
  17. this.user_name = user_name;
  18. }
  19. public String getUser_password() {
  20. return user_password;
  21. }
  22. public void setUser_password(String user_password) {
  23. this.user_password = user_password;
  24. }
  25. }
  1. //实体类Goods
  2. package com.hz.entity;
  3. public class Goods {
  4. private long goods_id;//商品id
  5. private String goods_title;//商品标题
  6. private int goods_browse;//商品浏览次数
  7. private int goods_state;//商品状态
  8. public long getGoods_id() {
  9. return goods_id;
  10. }
  11. public void setGoods_id(long goods_id) {
  12. this.goods_id = goods_id;
  13. }
  14. public String getGoods_title() {
  15. return goods_title;
  16. }
  17. public void setGoods_title(String goods_title) {
  18. this.goods_title = goods_title;
  19. }
  20. public int getGoods_browse() {
  21. return this.goods_browse;
  22. }
  23. public void setGoods_browse(int goods_browse) {
  24. this.goods_browse = goods_browse;
  25. }
  26. public int getGoods_state() {
  27. return this.goods_state;
  28. }
  29. public void setGoods_state(int goods_state) {
  30. this.goods_state = goods_state;
  31. }
  32. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注