创建数据库新建查询
写入代码
#设置数据的视图---使用数据库
use mydb;
#判断表存在就删除表
drop table if exists student;
#创建表
create table student
(stuId int primary key auto_increment,
stuName varchar(20),
stuSex varchar(2),
stuAge int,
stuAddr varchar(50))
#插入测试数据
insert into student(stuName,stuSex,stuAge,stuAddr) values('张三','男',20,'河南');
insert into student(stuName,stuSex,stuAge,stuAddr) values('小美','女',18,'山东');
insert into student(stuName,stuSex,stuAge,stuAddr) values('Rose','女',19,'美国');
insert into student(stuName,stuSex,stuAge,stuAddr) values('Jack','男',21,'英国');
#查询数据表
select * from student;
打开idea创建项目导入jar包
最好是与mysql版本一致
当出现为成功
链接数据库
首先确定数据库打开状态
其次配置链接参数
databaseName 指定的数据库名字
UTC现在的时间
MySQL 5.0版本:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/databaseName?useSSL=false&serverTimezone=UTC
username=root
password=123
MySQL 8.0版本:
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/databaseName?useSSL=false&serverTimezone=UTC
username=root
password=123
创建数据库对象
代码
package com.wenben;
public class Student {
private String stuId;
private String stuName;
private String stuSex;
private int stuAge;
private String stuAddr;
public Student() {
}
public Student(String stuId, String stuName, String stuSex, int stuAge, String stuAddr) {
this.stuId = stuId;
this.stuName = stuName;
this.stuSex = stuSex;
this.stuAge = stuAge;
this.stuAddr = stuAddr;
}
public String getStuId() {
return stuId;
}
public void setStuId(String stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuSex() {
return stuSex;
}
public void setStuSex(String stuSex) {
this.stuSex = stuSex;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
public String getStuAddr() {
return stuAddr;
}
public void setStuAddr(String stuAddr) {
this.stuAddr = stuAddr;
}
}
创建测试程序
注意要单独创建一个包存储测试类
package com.Text;
import org.junit.Test;
import java.sql.*;
public class StudentText {
@Test
public void textSelectAll() throws SQLException, ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC","root","root");
PreparedStatement pr=con.prepareStatement("select * from student");
ResultSet rs=pr.executeQuery();
while (rs.next()){
int stuId =rs.getInt("stuId");
String stuName =rs.getString("stuName");
String stuSex =rs.getString("stuSex");
int stuAge =rs.getInt("stuAge");
String stuAddr =rs.getString("stuAddr");
System.out.println(stuId+"-------"+stuName+"-------"+stuSex+"-------"+stuAge+"-------"+stuAddr);
}
if (rs!=null){rs.close();}
if (pr!=null){pr.close();}
if (con!=null){con.close();}
}
}