1、配置资源文件 .properties (driver, url,username,password) 便于后期更改
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=123456
2、编写utils 工具类,读取配置资源,加载数据库 ,关闭资源这些操作只要连接上了,基本上不需要再重复写代码。
package JavaSE.Lesson16;
import JavaSE.Lesson16.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestInsert {
public static void main(String[] args) {
Connection conn = null;
Statement st =null;
ResultSet rs =null;
try {
conn = JdbcUtils.getConnection();
st = conn.createStatement();
String sql = "INSERT INTO account(id,`name`,`money`)\n" +
"VALUES(3,'CC','20000.00')";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("插入成功!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn,st,rs);
}
}
}
3、编写数据库的增,删,改,查 主程序
3.1 删除
public class JdbcDelete {
public static void main(String[] args) {
Connection conn = null;
Statement st =null;
ResultSet rs =null;
try {
conn = JdbcUtils.getConnection();
st = conn.createStatement();
String sql = "DELETE FROM account WHERE id =3";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("删除成功!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn,st,rs);
}
}
}
3.2 插入
public class TestInsert {
public static void main(String[] args) {
Connection conn = null;
Statement st =null;
ResultSet rs =null;
try {
conn = JdbcUtils.getConnection();
st = conn.createStatement();
String sql = "INSERT INTO account(id,`name`,`money`)\n" +
"VALUES(3,'CC','20000.00')";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("插入成功!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn,st,rs);
}
}
}
3.3 更改 更新
public class JdbcUpdate {
public static void main(String[] args) {
Connection conn = null;
Statement st =null;
ResultSet rs =null;
try {
conn = JdbcUtils.getConnection();
st = conn.createStatement();
String sql = "UPDATE account SET `name`='AAAA',`money`='50000.00' WHERE id=1";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("更新成功!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn,st,rs);
}
}
}
3.4 查询 (executeQuery)
public class JdbcSelect {
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
st = conn.createStatement();
//sql
String sql = "SELECT * from account where id =1";
rs = st.executeQuery(sql);
while (rs.next()){
System.out.println(rs.getString("name"));;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn,st,rs);
}
}
}
标签:25,JDBC,rs,sql,st,JdbcUtils,2023,null,conn
From: https://www.cnblogs.com/RUI2022/p/17153892.html