【JavaWeb】使用JDBC增加查询Mysql数据库内容:
数据库:
自行建库建表,最少有两个字段(除主键 id 外)
后端:
新建项目模块
选择模块,添加依赖
配置文件:
db.properties
driver=com.mysql.cj.jdbc.Driver
user=root
url=jdbc:mysql://127.0.0.1:3306/csdn
password=ROOT
Java类:
- 题目一:使用preparedStatement 操作数据库,向面建的表插入数据
add增加
package com.swc;
import java.sql.*;
import java.util.ResourceBundle;
public class add {
// main
public static void main(String[] args) {
//ctrl alt l
//读取属性配置文件
ResourceBundle bundle = ResourceBundle.getBundle("com/swc/resources/db");
// ctrl alt v
String driver = bundle.getString("driver");
String user = bundle.getString("user");
String password = bundle.getString("password");
String url = bundle.getString("url");
// 放大 变量 作用域
Connection con = null;
Statement st = null;
ResultSet rs = null;
//注册驱动
try {
Class.forName(driver);
//类名调用 静态方法
//alt enter
//获取连接对象
con = DriverManager.getConnection(url, user, password);
//操作
st = con.createStatement();
//写sql语句
String sql = "insert into pone_jdbc(name,stuid) values('小明','1')";
//执行
st.execute(sql);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
//关闭
} finally {
//rs st con
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
- 运行add.java文件
- 数据库增加数据
- 题目二:使用preparedStatement 操作数据库,查询上面设计的表
query查询
package com.swc;
import java.sql.*;
import java.util.ResourceBundle;
public class query {
// main
public static void main(String[] args) {
//ctrl alt l
//读取属性配置文件
ResourceBundle bundle = ResourceBundle.getBundle("com/swc/resources/db");
// ctrl alt v
String driver = bundle.getString("driver");
String user = bundle.getString("user");
String password = bundle.getString("password");
String url = bundle.getString("url");
// 放大 变量 作用域
Connection con = null;
Statement st = null;
ResultSet rs = null;
//注册驱动
try {
Class.forName(driver);
//类名调用 静态方法
//alt enter
//获取连接对象
con = DriverManager.getConnection(url, user, password);
//操作
st = con.createStatement();
//写sql语句
String sql = "select * from pone_jdbc"; //查
rs = st.executeQuery(sql);
while (rs.next()) {
System.out.println("id:"+rs.getString(1));
System.out.println("name:"+rs.getString(2));
System.out.println("stuid:"+rs.getString(3));
} //查
//执行
st.execute(sql);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
//关闭
} finally {
//rs st con
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
- 运行query.java文件
- 控制台输出,查询到数据库内容