1、创建mysql测试表

java 连接mysql增删改查-LMLPHP

2、按下图创建3个文件夹与3个类

java 连接mysql增删改查-LMLPHP

3、三个类的代码

PersionDao :目录(Data Access Object), 数据访问对象是第一个面向对象的数据库接口

 package com.test.dao;

 import com.test.entity.Person;

 import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; /**
* Created by wdw on 2017/9/7.
*/
public class PersonDao { private final static String DRIVER = "com.mysql.jdbc.Driver";
private final static String URL = "jdbc:mysql://localhost:3306/wdw";
private final static String USERNAME = "root";
private final static String PASSWORD = "123456"; /**
* 添加一个人
*
* @param person
* @return boolean
*/
public boolean insert(Person person) {
boolean flag = false;//
try {
Class.forName(DRIVER);//加载数据库驱动
java.sql.Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
// 使用jar包中的connection接口,并通过DriveManager类的静态方法getConnection()创建连接对象conn
String sql = "INSERT INTO sys_users(id,name,code) VALUES(?,?,?)";//编写sql语句
PreparedStatement ps = conn.prepareStatement(sql);////创建预处理对象ps
ps.setInt(1, person.getId());
ps.setString(2, person.getName());
ps.setString(3, person.getCode()); if (ps.executeUpdate() > 0) {
flag = true;
}
System.out.print(flag);
ps.close();
conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
} /**
* 添加一个人
*
* @param id
* @return boolean
*/
public Person selectById(String id) {
Person p = new Person();
try {
Class.forName(DRIVER);//加载数据库驱动
java.sql.Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
String sql = "delete sys_users where id=" + id;//编写sql语句
PreparedStatement ps = conn.prepareStatement(sql);////创建预处理对象ps
ResultSet r = ps.executeQuery();
while (r.next()) {
p.setId(r.getInt("id"));
p.setName((r.getString("code")));
p.setCode(r.getString("name"));
} ps.close();
conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return p;
} }

entity:entity目录(实体),实体就是一个特定的软件模块。

 package com.test.entity;

 /**
* Created by wdw on 2017/9/7.
*/
public class Person { private int id;
private String code;
private String name; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getCode(){
return this.code; }
public void setCode(String code)
{
this.code=code; }
public String getName(){
return this.name; }
public void setName(String name)
{
this.name=name; }
}

test:test目录,最终的试行测试。

 package com.test.test;

 import com.test.dao.PersonDao;
import com.test.entity.Person; /**
* Created by wdw on 2017/9/7.
*/
public class test {
public static void main(String[] args) {
Person ps = new Person();
ps.setId(1);
ps.setCode("编号");
ps.setName("张三");
PersonDao s = new PersonDao();
boolean aResult = s.insert(ps); //add a use
boolean uResult = s.insert(ps); //delete a use
boolean dResult = s.insert(ps); //delete a use
} }

4、运行测试,记得在main断点。

java 连接mysql增删改查-LMLPHP

05-11 13:22