• Java DB访问(一) JDBC


    1. 项目说明
    项目采用 maven 组织 ,jdbc 唯一的依赖就是 mysql-connector-java pom 依赖如下:
     
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.30</version>
    </dependency>
    </dependencies>
     
    2 项目结构
     
     
    3 DB 脚本
    DROP TABLE IF EXISTS `account`;
    CREATE TABLE `account` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(45) DEFAULT NULL,
    `money` decimal(10,0) DEFAULT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=103 DEFAULT CHARSET=utf8;
     
    INSERT INTO `account` VALUES ('1', 'hbb0b0', '40000');
    INSERT INTO `account` VALUES ('2', 'kael', '1000');
    4 java 代码
     
    package hbb0b0.jdbc01;
     
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
     
    import com.mysql.jdbc.PreparedStatement;
     
    /**
    * App
    *
    */
    public class App {
     
    //DB URL
    private static final String URL = "jdbc:mysql://localhost:3306/study";
    private static final String NAME = "root";
    private static final String PASSWORD = "sqlsa";
     
    public static void main(String[] args) throws Exception {
     
    Class.forName("com.mysql.jdbc.Driver");
     
    // 连接数据库
    Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD);
     
    // 构造插入语句
    PreparedStatement psmt = (PreparedStatement) conn
    .prepareStatement("insert account(name,money) values(?,?)");
     
    /* insert */
     
    for (int i = 0; i < 100; i++) {
    // 参数赋值
    psmt.setString(1, String.format("hbb0b0-%d", i));
    psmt.setDouble(2, i);
    // 执行插入语句
    Boolean result = psmt.execute();
    // 插入语句执行结果
    System.out.println(result);
    }
     
    //构造select 语句
    Statement stmt = conn.createStatement();
     
    //执行select 语句
    ResultSet rs = stmt.executeQuery("select id,name,money from account");
     
    //输出查询结构
    while (rs.next()) {
    System.out.println(rs.getInt("id") + ", " + rs.getString("name")
    + ", " + rs.getDouble("money"));
    }
     
    }
    }
     
     
     
     
  • 相关阅读:
    租店笔记
    pycharm debug调试【Mute Breakpoints】【Run to Curson】按钮
    教师岗位职业技能分享—备课小秘籍
    交换机基础
    路由基础
    IPv6端口转发联机软件 4to6
    数据库_关键词用法
    1_Shell脚本入门
    MySQL_linux下mysql数据库自动定时备份
    Unity URP 安装配置
  • 原文地址:https://www.cnblogs.com/hbb0b0/p/8323580.html
Copyright © 2020-2023  润新知