1、创建一个user类
package chapter09;
import java.util.Date;
public class user {
private int id;
private String username;
private String password;
private String email;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
2、创建一个JDBCUtils
package chapter09;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtils {
public static Connection getCon() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc","root","123456");
return conn;
}
public static void realse(Statement stmt,Connection conn) {
if(stmt!=null) {
try {
stmt.close();
}catch(SQLException e) {
e.printStackTrace();
}
stmt=null;
}
if(conn!=null) {
try {
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
}
3、创建一个userdao
package chapter09;
import java.sql.Connection;
import java.sql.Statement;
import java.util.List;
public class userdao {
public boolean insert(user user) {
Connection conn=null;
Statement stmt=null;
try {
conn=JDBCUtils.getCon();
stmt=conn.createStatement();
java.util.Date birthday=user.getBirthday();
String sqlbirthday=String.format("%tF",birthday);
String sql="insert into users(id,name,password,email,birthday)"+"values('"
+user.getId()+"','"
+user.getUsername()+"','"
+user.getPassword()+"','"
+user.getEmail()+"','"
+sqlbirthday+"'"
+")";
System.out.println(sql);
int row=stmt.executeUpdate(sql);
if(row>0) {
return true;
}
}catch(Exception e) {
throw new RuntimeException(e);
}finally {
System.out.println("资源会被关闭吗");
JDBCUtils.realse(stmt, conn);
}
return false;
}
public List<user> findAlluser(){
List<user> list=null;
return list;
}
}
4、测试
package chapter09;
import java.util.Date;
public class jdbcInsertTest {
public static void main(String[] args) {
userdao dao=new userdao();
user user=new user();
user.setId(11);
user.setUsername("glc");
user.setPassword("2020080605032");
user.setEmail("glc@qq.com");
user.setBirthday(new Date());
boolean flag=dao.insert(user);
System.out.println(flag);
}
}