使用jdbc对mysql进行增删改查
2024-09-08 00:26:30
建立数据库和数据表
CREATE DATABASE `mysqlTest` DEFAULT CHARACTER SET utf8;
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`num_id` int(11) DEFAULT NULL,
`name` varchar(20) NOT NULL,
`f_name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
简单的demo
package sql; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; public class JDBCDemo{ public static void main(String[] args) throws SQLException{
insertFunction();
updateFunction();
queryFunction();
} public static void queryFunction() throws SQLException{
Connection temconn = getCon();
String sql = "SELECT id,f_name FROM test where id BETWEEN 2 AND 5 ";
try(PreparedStatement stmt = temconn.prepareStatement(sql)){
ResultSet rs = stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2));
//或者用列名做参数,可读性好,性能差一些
System.out.println(rs.getInt("id")+"\t"+rs.getString("f_name"));
}
}catch (SQLException e) {
e.printStackTrace();
// TODO: handle exception
}
temconn.close();
} public static void updateFunction() throws SQLException{
Connection temconn = getCon();
String sql = "UPDATE test SET f_name='update2' WHERE id BETWEEN 5 AND 10 ";
try(PreparedStatement stmt = temconn.prepareStatement(sql)){
int counts = stmt.executeUpdate();
System.out.println(counts);
}catch (SQLException e) {
e.printStackTrace();
// TODO: handle exception
}
temconn.close();
} public static void insertFunction() throws SQLException{
Connection temconn = getCon();
try {
//关闭自动提交,即开启事务
temconn.setAutoCommit(false);
for(int i=0;i<10;i++){
int id = i;
String sql = "INSERT INTO test (num_id,name,f_name) VALUES(?,?,?);";
try(PreparedStatement stmt = temconn.prepareStatement(sql)){
stmt.setInt(1, id);
stmt.setString(2, "娜娜"+id);
stmt.setString(3, "f娜娜3"+id);
stmt.execute();
}catch(Exception e){
e.printStackTrace();
}
}
//事务提交
temconn.commit();
} catch (SQLException e1) {
e1.printStackTrace();
//发生异常则回滚
temconn.rollback();
}
temconn.close();
} public static Connection getCon(){
Connection tmpconn = null;
System.out.println("初始化时执行了public static Connection getCon()");
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/mysqlTest?characterEncoding=UTF-8";
String UserName = "root";
String Password = "password";
tmpconn = DriverManager.getConnection(url, UserName, Password);
// tmpconn.setAutoCommit(false);
}catch(Exception e){
e.printStackTrace();
}
return tmpconn;
}
}
多线程安全的插入demo
package sql; import java.sql.Connection;
import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue; public class LearnJDBC implements Runnable{ private static LinkedBlockingQueue<Connection> conQueue = null;
//线程数
private static int threadCounts = 3;
// 每个线程的循环数
private static int forNumber = 3; public static void main(String[] args) throws InterruptedException{
System.out.println("---------------------导入开始"+getNowTime()+"--------------");
createConnections(threadCounts);
LearnJDBC st = new LearnJDBC();
for (int i = 0;i<threadCounts;i++){
new Thread(st,"线程:"+i).start();
}
} public static void insertFunction(String threadName) throws InterruptedException{
Connection temconn = conQueue.take();
int threadNumber = Integer.parseInt(threadName.split(":")[1]);
for(int i=0;i<forNumber;i++){
int id = i;
String sql = "INSERT INTO test (num_id,name,f_name) values(?,?,?);";
try(java.sql.PreparedStatement stmt = temconn.prepareStatement(sql)){
stmt.setInt(1, id*threadNumber);
stmt.setString(2, "娜娜"+id+":"+threadName);
stmt.setString(3, "f娜娜"+id+":"+threadName);
stmt.execute();
}catch(Exception e){
e.printStackTrace();
}
}
conQueue.put(temconn);
System.out.println(threadName+"---导入结束"+getNowTime()+"--------------");
} @Override
public void run() {
try {
insertFunction(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
} // 产生一个简易的连接池
public static void createConnections(int num){
try {
conQueue = getconQueue(num);
} catch (InterruptedException e) {
e.printStackTrace();
}
} public static LinkedBlockingQueue<Connection> getconQueue(int num) throws InterruptedException {
LinkedBlockingQueue<Connection> temconQueue = new LinkedBlockingQueue<Connection>();
for(int i=0; i<num; i++) {
temconQueue.put(getCon());
}
return temconQueue;
} public static Connection getCon(){
Connection tmpconn = null;
System.out.println("初始化时执行了public static Connection getCon()");
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/mysqlTest?characterEncoding=UTF-8";
String UserName = "root";
String Password = "password";
tmpconn = DriverManager.getConnection(url, UserName, Password);
// tmpconn.setAutoCommit(false);
}catch(Exception e){
e.printStackTrace();
}
return tmpconn;
} public static String getNowTime(){
return (new SimpleDateFormat("HH:mm:ss")).format(new Date());
} public static int getRandomNumber(int range){
int number = new Random().nextInt(range) + 1;
return number;
} }
最新文章
- machine learning----->;有监督学习和无监督学习的区别
- jsp学习--JSP运行原理,九大隐式对象和JSP常用标签
- 【Win10】UAP/UWP/通用 开发之 SplitView
- animation of android (2)
- jquery和js使用技巧
- javascript密码强度验证!
- js星级评分点击星级评论打分效果--收藏--转载
- 手算KMP匹配的Next值和Nextval值
- json转换成list map集合
- iframe 父子页面方法调用
- Java Draw
- WIN10REALTEL高清音频管理器如何调音?调音无效怎么办?
- Converting PDF to Text in C#
- SDOI2017 Round2 详细题解
- Eclipse搭建SSH框架(Struts2+Spring+Hibernate)
- X-PACK详解
- LOJ #6432. 「PKUSC2018」真实排名(组合数)
- Android编译系统入门(二)
- mvc ---- ajax 提交 (ckeditor)富文本框 提示潜在危险 Request.Form
- ggplot2学习
热门文章
- redis:安装配置主从
- 【BZOJ 2431】 [HAOI2009] 逆序对数列 (DP)
- [MVC]Controller
- 线性回归Linear regression
- VirtualBox - 虚拟机下主机与虚拟机、虚拟机与虚拟机之间通信配置
- 洛谷——P1262 间谍网络
- hdu6110(线段树+lca)
- 从 modCount 看 java集合 fail-fast 机制
- 教你如何查看CAD文件是哪个版本的来自http://blog.sina.com.cn/s/blog_4c9fa4dd0101il1v.html
- Codeforces554E:Love Triangles