1.写在前面
操作系统:
OS 名称: Microsoft Windows 10 专业版
OS 版本: 10.0.17763 Build 17763
数据库:
MySQL版本:Server version: 8.0.13 MySQL Community Server – GPL
Java:
java version “1.8.0_181”
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
javac 1.8.0_181
2.下载mysql-connector-j
去MySQL官网下载, 找到了下载地址:https://dev.mysql.com/downloads/connector/j/
3.添加Jar
在Eclipse项目中添加刚刚下载的jar
导入方法:
右击项目-》Build Path-》configure build path-》Add External JARs找到你的jar文件添加即可
4.新建一个测试数据库
1.创建数据库 test
mysql> create database test;
2.选用test
mysql> use test;
3.创建表 emp
mysql> create table emp
(
empno int,
ename char(16),
job char(16),
sal float
);
4.插入一些数据
mysql> insert into emp values(1001,"Jack","CEO",10000);
Query OK, 1 row affected (0.04 sec)
mysql> insert into emp values(1002,"Jhon","CFO",9000);
Query OK, 1 row affected (0.07 sec)
mysql> insert into emp values(1003,"Jane","DBA",5000);
Query OK, 1 row affected (0.07 sec)
5.检查一下
mysql>select * from emp;
OK!
5.编写Java程序
Test_1.java
package top.sencom.test11;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class Test_1 {
static Connection con;
static Statement sql;
static ResultSet res;
public Connection getConnection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("数据库驱动加载成功!");
} catch (ClassNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
try {
//问奇多得多
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false", "root", "123456");
System.out.println("数据库连接成功!");
}catch(SQLException e) {
e.printStackTrace();
}
return con;
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Test_1 c= new Test_1();
con=c.getConnection();
try {
sql=con.createStatement();
res=sql.executeQuery("select * from emp");
while(res.next()) {
String empno=res.getString("empno");
String ename=res.getString("ename");
String job=res.getString("job");
String sal=res.getString("sal");
System.out.print("|empno: "+empno);
System.out.print("|ename: "+ename);
System.out.print("|job: "+job);
System.out.print("|sal: "+sal);
System.out.println();
}
System.out.print("In put the empno:");
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
String no = sc.nextLine();
int re=sql.executeUpdate("delete from emp where empno = " + no);
if(re == 1) {
System.out.println("删除成功!");
}
else {
System.out.println("删除失败!");
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
记录的确成功删除了
在执行execute删除成功却返回false?
如果execute返回结果是 ResultSet 对象,则返回 true;如果结果是更新计数或者没有结果,则返回 false
意思就是如果是查询的话返回true,如果是更新或插入的话就返回false了。
所以使用executeUpdate进行删除比较好。
数据库连接问题
con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false”, “root”, “123456”);
MySQL8.0以后数据库 URL 需要声明是否使用 SSL 安全验证及指定服务器上的时区。
否则报错提示。