第一种比较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增删改查整体代码的更多相关文章

  1. mysql数据库的连接以及增删改查Java代码实现(转载)

    每天叫醒自己的不是闹钟,而是梦想 数据库: create table t1(id int primary key not null auto_increment,name varchar(32),pa ...

  2. java 连接mysql增删改查

    1.创建mysql测试表 2.按下图创建3个文件夹与3个类 3.三个类的代码 PersionDao :目录(Data Access Object), 数据访问对象是第一个面向对象的数据库接口 pack ...

  3. MySQL—增删改查,分组,连表,limit,union,alter,排序,去重

    MySQL增删改查 在表格的增删改查中,查的内容是最多的,包括group by ,join,limit,union,alter,排序都是服务于查的 #sql语句数据行操作补充 #增加: #insert ...

  4. mysql增删改查相关操作

    mysql增删改查相关操作 以前用mysql用的少,对于数据库相关的操作不熟悉,现在开始要接触数据库了,记录一下相关的基础操作吧. 1.数据库的授权操作 # mysql -u root -p Ente ...

  5. 基于gin的golang web开发:mysql增删改查

    Go语言访问mysql数据库需要用到标准库database/sql和mysql的驱动.标准库的Api使用比较繁琐这里再引入另一个库github.com/jmoiron/sqlx. go get git ...

  6. mvc模式jsp+servel+jdbc oracle基本增删改查demo

    mvc模式jsp+servel+jdbc oracle基本增删改查demo 下载地址

  7. PHP MySql增删改查

    mysql_connect()连接数据库 mysql_select_db选择数据库 mysql_fetch_assoc()获取结果集 mysql_query()执行sql语句 实例如下: <?p ...

  8. mysql增删改查练习

    Mysql增删改查sql语句练习 关于数据库的一些操作: 进入mysql 命令行: mysql -uroot –p 查看所有数据库: show databases; 创建数据库: create dat ...

  9. Django学习之mysql增删改查

    上节介绍了如何使用命令行操作mysql增删改查,现在介绍如何使用python管理mysql 使用pip 下载完mysql后,mysql会以pymysql模块的形式存储在pycharm的包文件里.我们通 ...

随机推荐

  1. 解决Unity的 The file &#39;MemoryStream&#39; is corrupted! Remove it and launch 崩溃问题

    孙广东   2015.7.30 问题:   在项目平时删除资源或者脚本资源时产生的prefab的脚本引用丢失,特别是在场景scene中丢了解决方式/// 1.又一次Clone项目/// 2.删除项目的 ...

  2. c语言数组小谈

    #include <stdio.h> #include <stdlib.h> #define N 5 int main() { double score[5]; int i; ...

  3. DB-MySQL:MySQL 复制表

    ylbtech-DB-MySQL:MySQL  复制表 1.返回顶部 1. MySQL 复制表 如果我们需要完全的复制MySQL的数据表,包括表的结构,索引,默认值等. 如果仅仅使用CREATE TA ...

  4. mongo服务器异常

    1.Detected unclean shutdown - /data/db/mongod.lock is not empty. 前几天把研究用的虚拟机直接关了回家过年,今天启动发现启动不了,报了个u ...

  5. Linux 系列- 基本命令

    Linux 基本命令 转自:http://www.taobaotest.com/blogs/qa?bid=353 Linux是一个基于命令的系统,它有很多很强的命令. 但它也有桌面系统,比如KDE, ...

  6. 小数据量csv文件数据导入数据库(思路)

    大致写写思路,因为sqlserver提供了可以直接导入的图形界面. 1.private static string GetConnectionString(string folderPath)  // ...

  7. ZBrush中标准笔刷介绍

    ZBrush最实用.精彩的部分便是雕刻了,笔刷又有时雕刻时必不可少的工具,ZBrush中给我们提供了很多种笔刷,那么,最基础.最常用的笔刷是什么呢,本文内容向大家介绍ZBrush®中标准笔刷以便大家熟 ...

  8. @DateTimeFormat无效原因

    一般都是使用@DateTimeFormat把传给后台的时间字符串转成Date,使用@JsonFormat把后台传出的Date转成时间字符串,但是@DateTimeFormat只会在类似@Request ...

  9. 边框的使用,border-radius,box-shadow,border-image

    <html>    <head>        <meta charset="UTF-8">        <title></ ...

  10. Hadoop HA 与 Federation

    最近在做Hadoop上应用开发,需要和HA集成,active name node 切换不能影响应用的运行.在研究HA背景的同时,发现HA和Federation 配置中共用了nameservices 的 ...