MYSQL数据库代码
#判断存在即删除数据库
drop database if exists mydb;
#创建数据库
create database mydb;
#使用数据库
use mydb;
#创建表
create table t_user
(
uid int primary key auto_increment,
username varchar(20),
password varchar(20),
phone varchar(11),
address varchar(50)
);
#插入数据
insert into t_user(username,password,phone,address) values('张三','666','18965423548','南阳');
insert into t_user(username,password,phone,address) values('李四','333','18754263548','许昌');
insert into t_user(username,password,phone,address) values('小美','123','18565234759','信阳');
insert into t_user(username,password) values('小','12893');
select * from t_user where username=? and password=?
select * from t_user;
drop table t_goods;
create table t_goods
(
gid int primary key auto_increment,
gname varchar(20),
price double,
mark varchar(100)
);
insert into t_goods(gname,price,mark) values('泡面',4.5,'够香够辣就是这个味!');
insert into t_goods(gname,price,mark) values('火腿',8.5,'肉质细腻Q弹!');
insert into t_goods(gname,price,mark) values('雪碧',3.5,'清爽冰凉随心爽!');
delete from t_goods where gid=1;
update t_goods set gname='鸡爪' where gid=4
select * from t_goods;
创建实体类Goods
package com.guo.dean;
public class Goods {
private Integer gid;
private String gname;
private Double price;
private String mark;
public Integer getGid() {
return gid;
}
public void setGid(Integer gid) {
this.gid = gid;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
@Override
public String toString() {
return "Goods{" +
"gid=" + gid +
", gname='" + gname + '\'' +
", price=" + price +
", mark='" + mark + '\'' +
'}';
}
}
在util包中创建JDBCUtil.java文件,编写JDBC代码(分层模式)
package com.guo.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class JDBCUtil {
//执行业务
public static String classname = "com.mysql.cj.jdbc.Driver";
public static String url = "jdbc:mysql://127.0.0.1:3306/mydb";
public static String user = "root";
public static String pwd = "root";
public static Connection connection = null;
public static ResultSet rs = null;
public static PreparedStatement ps = null;
public static Connection connection() {
try {
//添加驱动
Class.forName(classname);
//获取链接
connection = DriverManager.getConnection(url, user, pwd);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
public static void colse(ResultSet rs,PreparedStatement ps,Connection connection){
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (connection != null) {
connection.close();
}
} catch (Exception e) {
}
}
public static void colse(PreparedStatement ps,Connection connection){
try {