JDBC连接mysql增删改查整体代码
第一种比较low:用了statment,没有用preparedstatement。另外,插入时,不灵活,不能调用参数,但是如果直接给函数形参的话就会被SQL注入攻击,所以,最好在sql语句中使用?代表要引进的参数。
工具类(DBUtil类):用来连接和关闭数据库
package JDBC; /**
* Created by Administrator on 2018/3/8 0008.
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class DBUtil {
public static final String url="jdbc:mysql://127.0.0.1/bz?useSSL=false";
public static final String username="root";
public static final String password="root";
public static final String driver="com.mysql.jdbc.Driver";
public static Connection DBcon(){
Connection con=null;
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
con= DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
} public static void close(ResultSet rs,Statement stat,Connection conn){ try {
if(stat!=null)
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(conn!=null)
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(rs!=null)
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
测试类(Test类):其中有增删改查的功能,在测试类中写下sql语句,进行测试
package JDBC; /**
* Created by Administrator on 2018/3/8 0008.
*/
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static Connection conn=null;
public static Statement stat=null;
public static ResultSet rs=null;
public static void main(String[] args){
String select="select * from father;";
String insert="insert into father values(null,'POP');";
String update="update father set f_name='haha' where f_name='POP';";
String delete="delete from father where f_name='haha';";
conn=DBUtil.DBcon();
select(select);
insert(insert);
select(select);
update(update);
select(select);
delete(delete);
select(select);
DBUtil.close(rs,stat, conn);
}
public static void select(String quary){
try {
stat=conn.createStatement();
rs=stat.executeQuery(quary);
while(rs.next()){
System.out.println(rs.getObject("fid")+"|"+rs.getObject("f_name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void insert(String quary){
try {
stat=conn.createStatement();
int i=stat.executeUpdate(quary);
System.out.println("插入"+i+"行");
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void delete(String quary){
try {
stat=conn.createStatement();
int i=stat.executeUpdate(quary);
System.out.println("删除了"+i+"行");
} catch (SQLException e) {
e.printStackTrace();
} }
public static void update(String quary){
try {
stat=conn.createStatement();
int i=stat.executeUpdate(quary);
System.out.println("更改"+i+"行");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
第二种解决了第一种low方法的问题,并且还新增了方法调用和过程调用:使用了CallableStatement类
package com.weikun.jdbc; import jdk.internal.org.objectweb.asm.Type;
import org.junit.Test; import java.sql.*; /**
* Created by Administrator on 2018/3/12 0012.
*/
public class C {
@Test
public void testFun(){
Connection conn = null;
CallableStatement cs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bz?useUnicode=true&charactorCoding=UTF-8&useSSL=false", "root", "root");
cs=conn.prepareCall("{?=call f_1(?)}");
cs.registerOutParameter(1, Type.DOUBLE);
cs.setDouble(2,0.3); cs.execute();
System.out.println(cs.getObject(1));
}catch(Exception e){
e.printStackTrace();
}
} @Test
public void testProd(){
Connection conn = null;
CallableStatement cs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bz?useUnicode=true&charactorCoding=UTF-8&useSSL=false", "root", "root");
cs=conn.prepareCall("call p_1(?,?,?,?);");
cs.setInt(1,20005);
cs.setBoolean(2,true);
cs.setDouble(3,0.2);
cs.registerOutParameter(4, Types.FLOAT);
cs.execute();//返回的是第一个返回参数是不是个结果集,是的话返回1,不是的话返回0
System.out.println(cs.getObject(4));
}catch (Exception e){
e.printStackTrace();
}finally {
if(cs!=null){
try {
cs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} @Test
public void add() {
Connection connection = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bz?useUnicode=true&charactorCoding=UTF-8&useSSL=false", "root", "root");
ps=connection.prepareStatement("insert into e(v_name,v_salary) values(?,?)");
ps.setString(1,"jack");
ps.setDouble(2,3000);
System.out.println(ps.executeUpdate());
}catch (Exception e){
e.printStackTrace();
}finally {
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} @Test
public void del(){
Connection connection = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bz?useUnicode=true&charactorCoding=UTF-8&useSSL=false", "root", "root");
ps=connection.prepareStatement("DELETE from e where v_id=?");
ps.setInt(1,2);
System.out.println(ps.executeUpdate());
}catch (Exception e){
e.printStackTrace();
}finally {
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} @Test
public void update(){
Connection connection = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bz?useUnicode=true&charactorCoding=UTF-8&useSSL=false", "root", "root");
ps=connection.prepareStatement("UPDATE e SET v_name=? WHERE v_id=?");
ps.setString(1,"jack");
ps.setInt(2,1);
System.out.println(ps.executeUpdate());
}catch (Exception e){
e.printStackTrace();
}finally {
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} @Test
public void quaryCon(){
Connection connection=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bz?useUnicode=true&charactorCoding=UTF-8&useSSL=false","root","root");
ps=connection.prepareStatement("select * from products where prod_price>? and vend_id=?");
ps.setDouble(1,15.0);
ps.setInt(2,1003);
rs=ps.executeQuery();
while (rs.next()){
System.out.println(rs.getString("prod_name"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} @Test
public void quaryAll(){ //查询所有结果集,打印其中的某几列
Connection connection=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");//1、加载驱动
connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bz?useUnicode=true&charactorCoding=UTF-8&useSSL=false","root","root");
ps=connection.prepareStatement("select * from products");//尽量只用prepared态不使用Statment
rs=ps.executeQuery();//返回一个结果集
while(rs.next()){
System.out.println(rs.getObject("prod_id"));//从结果集中取出列名为prod_id的数据。
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} }
}
JDBC连接mysql增删改查整体代码的更多相关文章
- mysql数据库的连接以及增删改查Java代码实现(转载)
每天叫醒自己的不是闹钟,而是梦想 数据库: create table t1(id int primary key not null auto_increment,name varchar(32),pa ...
- java 连接mysql增删改查
1.创建mysql测试表 2.按下图创建3个文件夹与3个类 3.三个类的代码 PersionDao :目录(Data Access Object), 数据访问对象是第一个面向对象的数据库接口 pack ...
- MySQL—增删改查,分组,连表,limit,union,alter,排序,去重
MySQL增删改查 在表格的增删改查中,查的内容是最多的,包括group by ,join,limit,union,alter,排序都是服务于查的 #sql语句数据行操作补充 #增加: #insert ...
- mysql增删改查相关操作
mysql增删改查相关操作 以前用mysql用的少,对于数据库相关的操作不熟悉,现在开始要接触数据库了,记录一下相关的基础操作吧. 1.数据库的授权操作 # mysql -u root -p Ente ...
- 基于gin的golang web开发:mysql增删改查
Go语言访问mysql数据库需要用到标准库database/sql和mysql的驱动.标准库的Api使用比较繁琐这里再引入另一个库github.com/jmoiron/sqlx. go get git ...
- mvc模式jsp+servel+jdbc oracle基本增删改查demo
mvc模式jsp+servel+jdbc oracle基本增删改查demo 下载地址
- PHP MySql增删改查
mysql_connect()连接数据库 mysql_select_db选择数据库 mysql_fetch_assoc()获取结果集 mysql_query()执行sql语句 实例如下: <?p ...
- mysql增删改查练习
Mysql增删改查sql语句练习 关于数据库的一些操作: 进入mysql 命令行: mysql -uroot –p 查看所有数据库: show databases; 创建数据库: create dat ...
- Django学习之mysql增删改查
上节介绍了如何使用命令行操作mysql增删改查,现在介绍如何使用python管理mysql 使用pip 下载完mysql后,mysql会以pymysql模块的形式存储在pycharm的包文件里.我们通 ...
随机推荐
- hdu 4888 2014多校第三场1002 Redraw Beautiful Drawings 网络流
思路:一開始以为是高斯消元什么的.想让队友搞,结果队友说不好搞,可能是网络流.我恍然,思路立刻就有了. 我们建一个二部图.左边是行,右边是列,建个源点与行建边,容量是该行的和.列与新建的汇点建边.容量 ...
- Unity3D - 图形性能优化:优化着色器载入时间
Unity官方文档之"图形性能优化-优化着色器载入时间"的翻译,E文链接. Optimizing Shader Load Time 优化着色器载入时间 Shaders are sm ...
- win10怎样开启自带虚拟机
win10和win8一样.都有自带的虚拟机,可是功能没有一安装上就打开,非常多喜欢用自带的东西,那么win10自带的虚拟机怎样开启呢? 首先要找到控制面板,我们右键点击開始button,我们找到&qu ...
- HDU 1113 Word Amalgamation (map 容器 + string容器)
http://acm.hdu.edu.cn/showproblem.php?pid=1113 Problem Description In millions of newspapers across ...
- iOS 8使用Touch ID进行身份认证
iOS 8的SDK开放了Touch ID的接口.从WWDC的视频中能够看到Touch ID应用在两个方面:用于Key Chain加密和用于授权.iOS 8正式版公布以后我们能够看到Evernote的i ...
- [HDU 5542] The Battle of Chibi
[题目链接] http://acm.hdu.edu.cn/showproblem.php?pid=5542 [算法] 树状数组优化DP [代码] #include<bits/stdc++.h&g ...
- 杂项:WCF
ylbtech-杂项:WCF Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台. 整合了 ...
- vue中 router-link 传递参数以及获取
将所遇见的问题一步一步记录下来,不久便会成长 今天在修改前端(vue) BUG的时候遇见 router-link标签,传递参数到另一个页面,确不知道参数在另一个页面怎么接收,于是找度娘需求解决办法,最 ...
- mysql_udf_http(根据mysql表自动触发发送http请求)
下载 tar包wget http://mysql-udf-http.googlecode.com/files/mysql-udf-http-1.0.tar.gz解压tar -vzxf mysql-ud ...
- POJ 2346 DP or打表
这题 不算重复的数.. 就变成水题了. 思路: 1.打表 2.DP 打表的: // by SiriusRen #include <cstdio> using namespace std; ...