本文共 2274 字,大约阅读时间需要 7 分钟。
JDBC编程之数据增加,更改,查询,删除
1 package com.good.jdbc; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.Statement; 7 8 public class Main { 9 //1数据库连接的方法就独立出来了10 public static Connection getConnection(){11 Connection conn = null;12 try {13 Class.forName("com.mysql.jdbc.Driver");14 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db","root","");15 } catch (Exception e) {16 e.printStackTrace();17 }18 return conn;19 }20 //2然后编写一个同样是静态的向数据表中插入数据的方法21 public static void insert(){22 //获取数据库连接23 Connection conn = getConnection();24 try {25 String sql = "INSERT INTO tbl_user(name,password,email)" +26 "VALUES('Tom','123456','tom@gmail.com')";27 Statement st = conn.createStatement();28 int count = st.executeUpdate(sql);29 System.out.println("向用户表中插入了 " + count + " 条记录");30 conn.close();31 } catch (Exception e) {32 e.printStackTrace();33 }34 }35 //3接下来写一个更新的方法36 public static void update(){37 //获取数据库连接38 Connection conn = getConnection();39 try {40 String sql = "UPDATE tbl_user SET email='tom@126.com' WHERE name = 'Tom'";41 Statement st = conn.createStatement();42 int count = st.executeUpdate(sql);43 System.out.println("向用户表中更新了 " + count + " 条记录");44 conn.close();45 } catch (Exception e) {46 e.printStackTrace();47 }48 }49 //4删除记录的方法50 public static void delete(){51 //获取数据库连接52 Connection conn = getConnection();53 try {54 String sql = "DELETE FROM tbl_user WHERE name = 'TOM'";55 Statement st = conn.createStatement();56 int count = st.executeUpdate(sql);57 System.out.println("向用户表中删除了 " + count + " 条记录");58 conn.close();59 } catch (Exception e) {60 e.printStackTrace();61 }62 }63 public static void main(String[] args) {64 // insert();65 delete();66 update();67 }68 }
转载地址:http://oabsx.baihongyu.com/