JDBC实现简单的增删改查(Mysql连接&servlet实现)
程序员文章站
2024-03-06 10:32:19
...
JDBC实现简单的增删改查(servlet实现)——数据库连接
项目中包 类等结构:
数据库数据:
dept(部门表)封装:
package com.hp.bean;
public class Dept {
private Integer id;//部门编号
private String name;//部门名称
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Dept{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public Dept(Integer id, String name) {
this.id = id;
this.name = name;
}
public Dept() {
}
}
emp(员工表)封装
package com.hp.bean;
import javafx.scene.DepthTest;
import java.util.Date;
public class Emp {
private Integer id;//员工编号
private String name;//员工姓名
private String password;//密码
private String birthday;//出生日期
private String sex;//性别
//如果要关联部门信息
private Dept dept;
public Emp(Integer id, String name, String password, String birthday, String sex, Dept dept) {
this.id = id;
this.name = name;
this.password = password;
this.birthday = birthday;
this.sex = sex;
this.dept = dept;
}
public Emp() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
@Override
public String toString() {
return "Emp{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", birthday='" + birthday + '\'' +
", sex='" + sex + '\'' +
", dept=" + dept +
'}';
}
}
/**
* 连接数据库工具类
*/
public class DBHelper {
//连接到MySQL
static String url="jdbc:mysql://localhost:3306/mydb"//链接地址+数据库名
static String username="root"; // MySQL登录账号
static String password="root"; //MySQL登录密码
static String driver="com.mysql.jdbc.Driver"; //驱动
//通过静态代码块 加载驱动
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//拿到数据库连接对象
public Connection getConnetion(){
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//执行main方法 测试数据库连接 如果后台打印一个地址说明连接成功
public static void main(String[] args) {
System.out.println(getConnetion());
}
}
连接成功:
连接失败:
推荐阅读
-
JDBC实现简单的增删改查(Mysql连接&servlet实现)
-
Python实现MySQL操作的方法小结【安装,连接,增删改查等】
-
Python实现MySQL操作的方法小结【安装,连接,增删改查等】
-
mysql语句实现简单的增、删、改、查操作示例
-
php+mysql实现简单的增删改查功能
-
jsp+servlet实现最简单的增删改查代码分享
-
Nodejs连接mysql并实现增、删、改、查操作的方法详解
-
node连接mysql生成接口,vue通过接口实现数据的增删改查(一)
-
Java Maven:spring boot + Mybatis连接MySQL,通用mapper的增删改查,映射实现多表查询
-
mysql语句实现简单的增、删、改、查操作示例