Java基础-JDBC增(删改)测试

来源:互联网 发布:quartus5.0 mac 编辑:程序博客网 时间:2024/05/08 18:22

说明

  1. Maven依赖及数据库表建立同:JDBC连接测试
  2. 此处使用PreparedStatement接口代替Statement接口

测试类:JDBCExample

import java.sql.*;public class JDBCExample {    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";    static final String JDBC_URL = "jdbc:mysql://localhost/mysql";    static final String USER = "root";    static final String PASS = "mysql";    public static void main(String[] args) {        Connection conn = null;        PreparedStatement ps=null;        try {            Class.forName(JDBC_DRIVER);            System.out.println("Connecting to database...");            conn = DriverManager.getConnection(JDBC_URL, USER, PASS);            System.out.println("Success!");            System.out.println("Creating statement...");            System.out.println("Success!");            String sql;            sql = "insert into role values(?,?,?)";            ps=conn.prepareStatement(sql);            try {                ps.setInt(1, 7);                ps.setString(2, "会员");                ps.setString(3, "hy");            } catch (Exception e) {}            int i=ps.executeUpdate();            if(i>0){                System.out.println("Success!");            }else{                System.out.println("FAILED!");            }            ps.close();            conn.close();        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (ps != null) {                    ps.close();                }                if (conn != null) {                    conn.close();                }            } catch (Exception e2) {                e2.printStackTrace();            }        }    }}

测试

这里写图片描述
这里写图片描述

0 0