当前位置:   article > 正文

Java—jdbc数据库连接以及增删改查操作_java实现对数据库一个表的增删改查

java实现对数据库一个表的增删改查

 1、需要先下载jdbc jar包,然后添加到工程上面 

  1. package jdbctest;
  2. import org.junit.Test;
  3. import java.io.InputStream;
  4. import java.sql.Connection;
  5. import java.sql.Driver;
  6. import java.sql.DriverManager;
  7. import java.sql.SQLException;
  8. import java.util.Properties;
  9. public class ConnectTest {
  10. @Test
  11. public void coonect4() throws Exception {
  12. // 最终版,将账号信息进行配置化,先在模块下的src下建立配置文件,读取文件
  13. InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("mysql.propries");
  14. Properties pros = new Properties();
  15. pros.load(is);
  16. String url = pros.getProperty("url");
  17. String user = pros.getProperty("user");
  18. String password = pros.getProperty("password");
  19. String driver = pros.getProperty("driver");
  20. //加载驱动
  21. Class.forName(driver);
  22. Connection conn = DriverManager.getConnection(url,user,password);
  23. System.out.println(conn);
  24. }
  25. }

 配置文件 

 

PreparedStatement相比Statement的好处

1. PreparedStatement操作Blob的数据,而Statement做不到。
2. PreparedStatement可以实现更高效的批量操作。

3.解决Statement的拼串、sql问题
 

对数据库的增删改

  1. package com.ruqi.prepareStatment;
  2. import org.junit.Test;
  3. import java.io.InputStream;
  4. import java.sql.*;
  5. import java.text.SimpleDateFormat;
  6. import java.util.Properties;
  7. public class PrepareStatmentTest {
  8. // 通用的增删改
  9. public void updateCommonUpdate(String sql, Object ...args) {
  10. Connection conn = null;
  11. PreparedStatement ps = null;
  12. try {
  13. conn = PrepareStatmentTest.getConnection();
  14. ps = conn.prepareStatement(sql);
  15. for (int i = 0; i < args.length; i++) {
  16. ps.setObject(i + 1, args[i]);
  17. }
  18. ps.execute(); // 查询sql返回true,其他返回false
  19. ps.executeUpdate(); // 返回更新成功的条数
  20. }catch (Exception e){
  21. e.printStackTrace();
  22. }finally {
  23. PrepareStatmentTest.closeConnection(conn,ps);
  24. }
  25. }
  26. @Test
  27. public void updatesql(){
  28. String sql = "delete from Scores where id = ?;";
  29. updateCommonUpdate(sql,8);
  30. }
  31. // 对数据进行增删改操作
  32. @Test
  33. public void prepareStatmentUpdate() throws Exception {
  34. Connection conn = null;
  35. conn = PrepareStatmentTest.getConnection();
  36. // 预编译sql,创建preparesstament对象
  37. String sql = "insert into Scores(id,score,date)values(?,?,?)"; //?表示点位符
  38. PreparedStatement ps = conn.prepareStatement(sql);
  39. // 填充点位符
  40. ps.setInt(1,8); // 下标按从1开始计算,并且每个数据要指定相应类型
  41. ps.setDouble(2,9.3);
  42. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  43. java.util.Date date = sdf.parse("2022-01-01");
  44. ps.setDate(3, new Date(date.getTime()));
  45. // 执行sql
  46. ps.execute();
  47. PrepareStatmentTest.closeConnection(conn,ps);
  48. }
  49. public static Connection getConnection() throws Exception {
  50. // 获取链接
  51. InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("mysql.propries");
  52. Properties pros = new Properties();
  53. pros.load(is);
  54. String url = pros.getProperty("url");
  55. String user = pros.getProperty("user");
  56. String password = pros.getProperty("password");
  57. String driver = pros.getProperty("driver");
  58. //加载驱动
  59. Class.forName(driver);
  60. //获取连接
  61. Connection conn = DriverManager.getConnection(url,user,password);
  62. return conn;
  63. }
  64. public static void closeConnection(Connection conn, PreparedStatement ps){
  65. if(ps!=null){
  66. try {
  67. ps.close();
  68. }catch (Exception e){
  69. e.printStackTrace();
  70. }
  71. }
  72. if(conn!=null){
  73. try {
  74. conn.close();
  75. }catch (Exception e){
  76. e.printStackTrace();
  77. }
  78. }
  79. }
  80. }

对数据库进行查询操作

  1. package com.ruqi.prepareStatment;
  2. import org.junit.Test;
  3. import java.io.InputStream;
  4. import java.lang.reflect.Field;
  5. import java.net.CookieHandler;
  6. import java.sql.*;
  7. import java.util.Properties;
  8. public class SelectSQL {
  9. @Test
  10. public void queryScore() {
  11. String sql = "select score from Scores where id = ?;";
  12. ScoresObject score = scoreCommonSelect(sql, 2);
  13. System.out.println(score);
  14. }
  15. // 针对不同表多行数据的通用查询
  16. public <T> List<T> commonManySelect(Class<T> clazz, String sql, Object... args) {
  17. Connection conn = null;
  18. PreparedStatement ps = null;
  19. ResultSet rs = null;
  20. try {
  21. conn = ConnectUtil.getConnection();
  22. ps = conn.prepareStatement(sql);
  23. for (int i = 0; i < args.length; i++) {
  24. ps.setObject(i + 1, args[i]);
  25. }
  26. rs = ps.executeQuery();
  27. ResultSetMetaData rsmeta = rs.getMetaData();
  28. ArrayList<T> list = new ArrayList<T>();
  29. while (rs.next()) {
  30. T t = clazz.newInstance();
  31. for (int i = 0; i < rsmeta.getColumnCount(); i++) {
  32. Object columnValue = rs.getObject(i + 1);
  33. String columnLabel = rsmeta.getColumnLabel(i + 1);
  34. Field decColumnName = clazz.getDeclaredField(columnLabel);
  35. decColumnName.setAccessible(true);
  36. decColumnName.set(t, columnValue);
  37. }
  38. list.add(t);
  39. }
  40. return list;
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. } finally {
  44. ConnectUtil.closeConnection(conn, ps, rs);
  45. }
  46. return null;
  47. }
  48. // 针对不同表一行数据的通用查询
  49. public <T> T commonSelect(Class<T> clazz, String sql, Object... args) {
  50. Connection conn = null;
  51. PreparedStatement ps = null;
  52. ResultSet rs = null;
  53. try {
  54. conn = ConnectUtil.getConnection();
  55. ps = conn.prepareStatement(sql);
  56. for (int i = 0; i < args.length; i++) {
  57. ps.setObject(i + 1, args[i]);
  58. }
  59. rs = ps.executeQuery();
  60. ResultSetMetaData rsmeta = rs.getMetaData(); //获取元数据,通过这个对象获取数据的个数
  61. if (rs.next()) {
  62. T t = clazz.newInstance();
  63. for (int i = 0; i < rsmeta.getColumnCount(); i++) {
  64. // 获取列值
  65. Object columnValue = rs.getObject(i + 1);
  66. // 获取列名,不推荐使用
  67. // String columnName = rsmeta.getColumnName(i + 1);
  68. // 获取别名,为了解决对象属性与数据表的列名不完全一致的情况,
  69. // 解决方法是:写sql时,对每个字段取别名,别名要跟对象属性一致,就可以解决上述问题
  70. String columnLabel = rsmeta.getColumnLabel(i + 1);
  71. Field decColumnName = clazz.getDeclaredField(columnLabel);
  72. decColumnName.setAccessible(true);
  73. decColumnName.set(t, columnValue);
  74. }
  75. return t;
  76. }
  77. } catch (Exception e) {
  78. e.printStackTrace();
  79. } finally {
  80. ConnectUtil.closeConnection(conn, ps, rs);
  81. }
  82. return null;
  83. }
  84. // 针对一个表一行数据的通用查询
  85. public ScoresObject scoreCommonSelect(String sql, Object... args) {
  86. Connection conn = null;
  87. PreparedStatement ps = null;
  88. ResultSet rs = null;
  89. try {
  90. conn = ConnectUtil.getConnection();
  91. ps = conn.prepareStatement(sql);
  92. for (int i = 0; i < args.length; i++) {
  93. ps.setObject(i + 1, args[i]);
  94. }
  95. rs = ps.executeQuery();
  96. ResultSetMetaData rsmeta = rs.getMetaData(); //获取元数据,通过这个对象获取数据的个数
  97. if (rs.next()) {
  98. ScoresObject soc = new ScoresObject();
  99. for (int i = 0; i < rsmeta.getColumnCount(); i++) {
  100. // 获取列值
  101. Object columnValue = rs.getObject(i + 1);
  102. // 获取列名,不推荐使用
  103. // String columnName = rsmeta.getColumnName(i + 1);
  104. // 获取别名,为了解决对象属性与数据表的列名不完全一致的情况,
  105. // 解决方法是:写sql时,对每个字段取别名,别名要跟对象属性一致,就可以解决上述问题
  106. String columnLabel = rsmeta.getColumnLabel(i + 1);
  107. Field decColumnName = ScoresObject.class.getDeclaredField(columnLabel);
  108. decColumnName.setAccessible(true);
  109. decColumnName.set(soc, columnValue);
  110. }
  111. return soc;
  112. }
  113. } catch (Exception e) {
  114. e.printStackTrace();
  115. } finally {
  116. ConnectUtil.closeConnection(conn, ps, rs);
  117. }
  118. return null;
  119. }
  120. @Test
  121. public void selectSql() {
  122. Connection conn = null;
  123. PreparedStatement ps = null;
  124. ResultSet rs = null;
  125. try {
  126. conn = ConnectUtil.getConnection();
  127. String sql = "select * from Scores where id = ?;";
  128. ps = conn.prepareStatement(sql);
  129. ps.setObject(1,2);
  130. // 获取结果集
  131. rs = ps.executeQuery();
  132. //处理结果集
  133. if(rs.next()){//判断是否有数据,如果有,指针下移并返回true
  134. //获取结果集的各个数据
  135. int id = rs.getInt(1);
  136. double score = rs.getInt(2);
  137. Date date = rs.getDate(3);
  138. //ORM思想:对象关系映射,将每个结果集都放到一个对象,每个对象表示一行数据,对象的数据表示每列的值
  139. ScoresObject result = new ScoresObject(id, score, date);
  140. System.out.println(result);
  141. }
  142. }catch (Exception e){
  143. e.printStackTrace();
  144. }finally {
  145. ConnectUtil.closeConnection(conn,ps,rs);
  146. }
  147. }
  148. }
  149. ==================================================
  150. package com.ruqi.prepareStatment;
  151. import java.io.InputStream;
  152. import java.sql.Connection;
  153. import java.sql.DriverManager;
  154. import java.sql.PreparedStatement;
  155. import java.sql.ResultSet;
  156. import java.util.Properties;
  157. public class ConnectUtil {
  158. public static Connection getConnection() throws Exception {
  159. // 获取链接
  160. InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("mysql.propries");
  161. Properties pros = new Properties();
  162. pros.load(is);
  163. String url = pros.getProperty("url");
  164. String user = pros.getProperty("user");
  165. String password = pros.getProperty("password");
  166. String driver = pros.getProperty("driver");
  167. //加载驱动
  168. Class.forName(driver);
  169. //获取连接
  170. Connection conn = DriverManager.getConnection(url,user,password);
  171. return conn;
  172. }
  173. public static void closeConnection(Connection conn, PreparedStatement ps, ResultSet rs){
  174. if(ps!=null){
  175. try {
  176. ps.close();
  177. }catch (Exception e){
  178. e.printStackTrace();
  179. }
  180. }
  181. if(conn!=null){
  182. try {
  183. conn.close();
  184. }catch (Exception e){
  185. e.printStackTrace();
  186. }
  187. }if(rs!=null){
  188. try {
  189. rs.close();
  190. }catch (Exception e){
  191. e.printStackTrace();
  192. }
  193. }
  194. }
  195. }
  196. ====================================================
  197. package com.ruqi.prepareStatment;
  198. import java.math.BigDecimal;
  199. import java.sql.Date;
  200. public class ScoresObject {
  201. private int id;
  202. private BigDecimal score;
  203. private Date date;
  204. public ScoresObject() {
  205. }
  206. public ScoresObject(int id, double score, Date date) {
  207. }
  208. public int getId() {
  209. return id;
  210. }
  211. public void setId(int id) {
  212. this.id = id;
  213. }
  214. public BigDecimal getScore() {
  215. return score;
  216. }
  217. public void setScore(BigDecimal score) {
  218. this.score = score;
  219. }
  220. public Date getDate() {
  221. return date;
  222. }
  223. public void setDate(Date date) {
  224. this.date = date;
  225. }
  226. @Override
  227. public String toString() {
  228. return "ScoresObject{" +
  229. "id=" + id +
  230. ", score=" + score +
  231. ", date=" + date +
  232. '}';
  233. }
  234. }

操作blob大数据类型

  1. package com.ruqi.prepareStatment;
  2. import org.junit.Test;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.InputStream;
  7. import java.sql.Blob;
  8. import java.sql.Connection;
  9. import java.sql.PreparedStatement;
  10. import java.sql.ResultSet;
  11. public class InsertBlob {
  12. // 数据库的blob类型分别对应存储的最大值:tinyblob=255b; blob=65K; mediumblob=16M; longblob=4G
  13. @Test
  14. public void insertBlob() throws Exception {
  15. Connection conn = ConnectUtil.getConnection();
  16. String sql = "insert into Scores(photo) values (?);";
  17. PreparedStatement ps = conn.prepareStatement(sql);
  18. FileInputStream inputstream = new FileInputStream(new File("img.png"));
  19. ps.setBlob(1,inputstream);
  20. ps.executeUpdate();
  21. ConnectUtil.closeConnection(conn,ps,null);
  22. }
  23. @Test
  24. public void selectBlob() throws Exception {
  25. Connection conn = ConnectUtil.getConnection();
  26. String sql = "select photo from Scores where id = ?;";
  27. PreparedStatement ps = conn.prepareStatement(sql);
  28. ps.setObject(1,7);
  29. ResultSet rs = ps.executeQuery();
  30. if(rs.next()){
  31. Blob photo = rs.getBlob("photo");
  32. InputStream is = photo.getBinaryStream();
  33. FileOutputStream fos = new FileOutputStream("test.png");
  34. byte[] buffer = new byte[1024];
  35. int len;
  36. while ((len = is.read(buffer)) != -1){
  37. fos.write(buffer,0 ,len);
  38. }
  39. fos.close();
  40. is.close();
  41. }
  42. ConnectUtil.closeConnection(conn,ps,rs);
  43. }
  44. }

批量插入数据

  1. public void insertManyData() {
  2. //由于mysql默认不支持批处理,因此需要在配置文件加以下配置url=jdbc:mysql://10.0.2.4:63306/test1111111?rewriteBatchedstatements=true
  3. Connection conn = null;
  4. PreparedStatement ps = null;
  5. try{
  6. conn = ConnectUtil.getConnection();
  7. String sql = "insert into Scores (id) values(?);";
  8. ps = conn.prepareStatement(sql);
  9. conn.setAutoCommit(false);//设置为不自动提前
  10. for (int i = 0; i <= 20000; i++) {
  11. ps.setObject(1,i);
  12. ps.addBatch();//攒sql
  13. if(i % 500 == 0 ){
  14. System.out.println(1);
  15. ps.executeBatch(); // 每攒500条执行一次
  16. ps.clearBatch();// 清除sql
  17. }
  18. }
  19. conn.commit();
  20. }catch (Exception e){
  21. e.printStackTrace();
  22. }finally {
  23. ConnectUtil.closeConnection(conn,ps,null);
  24. }
  25. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/575444
推荐阅读
相关标签
  

闽ICP备14008679号