创建数据库
表的属性
在表中加一些数据
连接数据库
点击file->project structure->点击加号选择jars or directories加入mysql连接jar包
编写代码
import java.sql.*;
public class MysqlTest {
// 连接数据库
public static Connection getConnection() {
Connection con = null; // 声明连接
try {
Class.forName("com.mysql.jdbc.Driver");
// 声明驱动
con = DriverManager.getConnection(
//我这里的数据库名是student user是root 没有密码
"jdbc:mysql://localhost:3306/student", "root", "");
System.out.println("连接成功");
} catch (Exception e) {
e.printStackTrace();
}
return con; // 返回连接
}
//增
public static void addUser(int id, String name, int age, String sex) {
Connection con = getConnection();
Statement st = null;
try {
st = con.createStatement();
String sql = "Insert into stu (id, name, age, sex)values('" + id + "', '" + name + "','" + age + "' ,'" + sex + "')";
st.execute(sql);
System.out.println("插入成功");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//删
public static void deleteUser(int id) {
Connection con = getConnection();
Statement st = null;
try {
st = con.createStatement();
String sql = "delete from stu where id='" + id + "' ";
st.execute(sql);
System.out.println("删除成功");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//改
public static void updateUser(int id, String name, int age, String sex) {
Connection con = getConnection();
Statement st = null;
try {
st = con.createStatement();
String sql = "update stu set name='" + name + "' ,age='" + age + "', sex='" + sex + "' where id='" + id + "'";
st.execute(sql);
System.out.println("修改成功");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//查
public static void search() {
Connection con = MysqlTest.getConnection();
Statement st = null;
ResultSet rs = null;
try {
st = con.createStatement();
String sql = "Select * from stu";
rs = st.executeQuery(sql);
System.out.println("查询结果如下:\n");
while (rs.next()) {
System.out.println("id:" + rs.getInt("id") + " name:" + rs.getString("name")
+ " age:" + rs.getInt("age") + " sex:" + rs.getString("sex"));
}
System.out.println("\n");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
运行
public class start {
public static void main(String[] args) {
// MysqlTest.addUser(4,"所示",23,"男");
// MysqlTest.deleteUser(4);
MysqlTest.updateUser(1,"aa",11,"nv");
MysqlTest.search();
}
}