一、准备工作,安装数据库(mysql,oracle等)
略
二、
1)打开IDEA,创建一个新的project
2)在新创建的project下新建一个Directory,用于存放连接mysql数据库需要使用的jar包。命名为libs。之后把“mysql-connector-java-5.1.42.jar”包粘贴进去。
3)选中该project,使用快捷键control+shift+alt+s,在左边窗口选择Modules,右边窗口选择Dependencies,点击图中“”+“”号,把jar包添加进去,再点apply。
4)到这里,基本上已经创建成功,接下来就是代码部分。
import java.sql.*; /** * @author Vi * @create 2018-07-28 * 测试数据库 */ public class jdbcTest { //mysql驱动包名 private static final String DRIVER_NAME = "com.mysql.jdbc.Driver"; //数据库连接地址 private static final String URL = "jdbc:mysql://127.0.0.1:3306/shopmanagement"; //用户名 private static final String USER_NAME = "root"; //密码 private static final String PASSWORD = "root"; public static void main(String[] args) { Connection conn = null; try { //加载mysql的驱动类 Class.forName(DRIVER_NAME); //获取数据库连接 conn = DriverManager.getConnection(URL,USER_NAME,PASSWORD); //mysql查询语句 String sql = "SELECT * FROM demo"; PreparedStatement prst = conn.prepareStatement(sql); //结果集 ResultSet rs = prst.executeQuery(); while(rs.next()) { System.out.println("用户名:" +rs.getString("name")+"----密码:"+rs.getString("password")); } rs.close(); prst.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
测试结果:
三、JDBC开发步骤
-
- 导入jar包
- 加载驱动程序
Class.forName(“com.mysql.jdbc.Driver”); //固定写法 -
获取数据库连接
Connection connection = DriverManager.getConnection(url,user,password);
url格式:
主协议:子协议://主机:端口/数据库名称
jdbc :mysql :// localhost:3306/mydatabase
user:数据库用户名
password:连接数据库密码DriverManager类:管理JDBC驱动服务类,主要功能是获取Connection对象
- 通过Connection创建Statement对象
Connection类: 代表数据库连接,要想访问数据库,必须先获得数据库连接 - 使用Statement对象来执行SQL语句,CRUD等操作,返回一个ResultSet对象
-
ResultSet操作结果集
next()方法:用于判断是否有下一条记录。如果有返回true,并且让游标向下移动一行,如果没有返回false。getXxx()方法:获取当前游标指向的这条记录中的列数据。如:getInt(),getString(),getDate(),getDouble()等
- 回收资源
四、JDBC相应API简介。
(1)定义记录的类
class Person { private String id; private String name; private String sex; private String age; public Person(String name,String sex,String age) { this.name = name; this.sex = sex; this.age = age; this.id = null; //default } public String getName() { return name; } public String getSex() { return sex; } public String getAge() { return age; } public void setName(String name) { this.name = name; } public void setSex(String sex) { this.sex = sex; } public void setAge(String age) { this.age = age; } }
2)获取连接
private static Connection getConnection() { String driver ="com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "root"; Connection conn = null; try { Class.forName(driver); //加载对应驱动 conn = DriverManager.getConnection(url,user,password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; }
3)insert
private static int insert(Person person) { Connection conn = getConnection(); int i = 0; String sql = "insert into person (name,sex,source) values(?,?,?)"; PreparedStatement pstmt =null; try { pstmt = (PreparedStatement) conn.prepareStatement(sql); pstmt.setString(1,person.getName()); pstmt.setString(2,person.getSex()); pstmt.setString(3,person.getFrom()); i = pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } return i; }
4)update
private static int update(Person person) { Connection conn = getConnection(); int i = 0; String sql = "update person set source='"+person.getFrom()+"' where name='"+person.getName()+"'"; PreparedStatement pstmt; try { pstmt = (PreparedStatement)conn.prepareStatement(sql); i = pstmt.executeUpdate(); System.out.println("result:"+i); pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return i; }
5)select
private static void getAll() { Connection conn = getConnection(); String sql = "select * from person"; PreparedStatement pstmt = null; try { pstmt = (PreparedStatement)conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); int col = rs.getMetaData().getColumnCount(); System.out.println("========================================="); while(rs.next()) { for (int i = 1; i <= col; i++) { System.out.print(rs.getString(1)+"\t"); if((i==2) && (rs.getString(i).length() < 8)) { System.out.print("\t"); } } System.out.println(); } System.out.println("========================================="); pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
6)delete
private static int delete(String name) { Connection conn = getConnection(); int i = 0; String sql = "delete from person where name='"+name+"'"; PreparedStatement pstmt = null; try { pstmt = (PreparedStatement)conn.prepareStatement(sql); i = pstmt.executeUpdate(); System.out.print("删除了:"+i+"条数据"); } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return i; }
测试:
public static void main(String[] args) { //增加数据 // Person p1 = new Person("爱德华艾尔利克","男","钢之炼金术师"); // Person p2 = new Person("温莉洛克贝尔","女","钢之炼金术师"); // // System.out.println(insert(p1)); // System.out.println(insert(p2)); //修改 // Person p = new Person("樱木花道","男","灌篮高手"); // update(p); //删除 System.out.println(delete("爱德华艾尔利克")); //查询 getAll(); }
测试结果:
代码分析
在上述对数据库进行增删改查的过程中,可以发现其共性部分,即通用的流程:
(1)创建Connection对象、SQL查询命令字符串;
(2)对Connection对象传入SQL查询命令,获得PreparedStatement对象;
(3)对PreparedStatement对象执行executeUpdate()或executeQurey()获得结果;
(4)先后关闭PreparedStatement对象和Connection对象。
可见,使用JDBC时,最常打交道的是Connection、PreparedStatement这两个类,以及select中的ResultSet类