一、往db3数据库中的account表添加数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class demo1 {
public static void main(String[] args){
Statement stmt = null;
Connection conn = null;
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//定义sql
String sql="insert into account values(null,'王五',3000)";
//获取Connection对象
conn = DriverManager.getConnection("jdbc:mysql:///db3","root","admin");
//获取执行sql的对象,Statement
stmt = conn.createStatement();
//执行sql
int count = stmt.executeUpdate(sql); //count为影响的行数
System.out.println(count);
if(count>0){
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
//stmt.close();
//释放资源
//避免空指针异常
if(stmt!=null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
二、修改记录
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import static java.lang.Class.forName;
public class demo2 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt =null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql///db3", "root", "admin");
String sql = "Update account set balance = 1500 where id =3";
stmt = conn.createStatement();
int count = stmt.executeUpdate(sql);
System.out.println(count);
if (count > 0) {
System.out.println("更新成功");
}else{
System.out.println("修改失败");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
if(stmt!=null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
三、删除一条记录
import java.sql.*;
import static java.lang.Class.forName;
public class demo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("mysql:///db3", "root", "admin");
String sql = "delete from account where id=3";
stmt = conn.createStatement();
int count = stmt.executeUpdate(sql);
System.out.println(count);
if(count!=0){
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}