Java DB访问之 JDBC
Posted hbb0b0
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java DB访问之 JDBC相关的知识,希望对你有一定的参考价值。
- 项目说明
项目采用 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")); } } }
以上是关于Java DB访问之 JDBC的主要内容,如果未能解决你的问题,请参考以下文章