java jdbc增删改查操作:
package com.gordon.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class jdbc01 {
public static void main(String[] args) {
// selectFunction();
// insertFunction();
// updateFunction();
// deleteFunction();
}
public static void deleteFunction() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
String sql = "DELETE FROM user WHERE ID = ?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, "4");
int res = st.executeUpdate();
if (res > 0) {
System.out.println("delete success.");
} else if (res == 0) {
System.out.println("deleted.");
} else {
System.out.println("delete faild.");
}
st.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void updateFunction() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
String sql = "UPDATE user SET name = ? WHERE ID = ?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, "zhangsan");
st.setString(2, "4");
int res = st.executeUpdate();
if (res > 0) {
System.out.println("update success.");
} else {
System.out.println("update faild.");
}
st.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void insertFunction() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
String sql = "INSERT INTO user (name) VALUES (?)";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, "name");
int res = st.executeUpdate();
if (res > 0) {
System.out.println("insert success.");
} else {
System.out.println("insert faild.");
}
st.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void selectFunction() {
try {
// 1.设置驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
// 3.sql语句
String sql = "SELECT * FROM user";
// 3.获取SQL执行者
PreparedStatement st = conn.prepareStatement(sql);
// 4.设置参数
// 5.执行sql语句
ResultSet rs = st.executeQuery();
// 6.处理数据
while (rs.next()) {
System.out.println(rs.getString("id") + ":" + rs.getString("name"));
}
// 7.释放资源
rs.close();
st.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}