jdbc数据库操作

时间:2021-11-18 15:42:09
package com.jikexueyuan.jdbc;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;




public class JDBCTest {


public static Connection getConnection(){
Connection con = null;
String url = null;
try {
Class.forName("com.mysql.jdbc.Driver");
url ="jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8&useSSL=false";
con = DriverManager.getConnection(url, "root", "201211");
}catch(Exception e) {
e.printStackTrace();
}
return con;
}
public static void insert(){
Connection con = getConnection();
try {
String sql = "INSERT INTO jsp_db.tbl_user (id, name, password, email) VALUES ('3', '张三', '123456', '111111');";
Statement st = con.createStatement();
int count = st.executeUpdate(sql);
System.out.println("用户向表中添加了"+count+"条数据");
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void update(){
Connection con = getConnection();
try {
String sql = "update jsp_db.tbl_user set email='121212' where name = '张三'";
Statement st = con.createStatement();
int count = st.executeUpdate(sql);
System.out.println("用户向表中修改了"+count+"条数据");
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void delete(){
Connection con = getConnection();
try {
String sql = "delete from jsp_db.tbl_user where name = '张三'";
Statement st = con.createStatement();
int count = st.executeUpdate(sql);
System.out.println("用户向表中删除了"+count+"条数据");
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void query(){
Connection con = getConnection();
try {
String sql = "SELECT * FROM jsp_db.tbl_user";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
System.out.print(rs.getInt(1)+"  ");
System.out.print(rs.getString(2)+"  ");
System.out.print(rs.getString(3)+"  ");
System.out.print(rs.getString(4)+"  ");
System.out.println();
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// update();
// insert();
delete();
query();
}
}