package com.jikexueyuan.jdbc;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
public class JDBCTest {
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");//注册驱动程序;Class为封装:jvm中类的信息
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root", "");//获取数据库的连接:url 用户名 密码
//jsp_db为数据库软件中创建的数据库
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void insert(){
Connection conn = getConnection();
try {
String sql = "INSERT INTO tbl_user(name,password,email)"+
"VALUES('Tom','123456','[email protected]')";
Statement st = conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println("向用户表中插入了"+count+" 条记录");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void update(){
Connection conn = getConnection();
try {
String sql = "UPDATE tbl_user SET email='[email protected]' WHERE name = 'Tom'";//更改邮箱
Statement st = conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println("向用户表中更新了"+count+" 条记录");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void delete(){
Connection conn = getConnection();
try {
String sql = "DELETE FROM tbl_user WHERE name = 'Tom'";
Statement st = conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println("从用户表中删除了"+count+" 条记录");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// String sql = "SELECT *FROM tbl_user";
// Connection conn = null;
// Statement st = null;
// ResultSet rs = null;
//
// try {
// Class.forName("com.mysql.jdbc.Driver");//注册驱动程序;Class为封装:jvm中类的信息
// conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root", "");//获取数据库的连接:url 用户名 密码
// //jsp_db为数据库软件中创建的数据库
// st = conn.createStatement();
// rs = st.executeQuery(sql);
// while (rs.next()) {
// System.out.print(rs.getInt("id")+" ");
// System.out.print(rs.getString("name")+" ");
// System.out.print(rs.getString("password")+" ");
// System.out.print(rs.getString("email")+" ");
// System.out.println();
// }
//
//
// } catch (Exception e) {
// e.printStackTrace();
// }finally{
// try {
// rs.close();
// } catch (Exception e2) {
//
// }
//
// try {
// st.close();
// } catch (Exception e3) {
// // TODO: handle exception
// }
//
// try {
// conn.close();
// } catch (Exception e4) {
// // TODO: handle exception
// }
// }
//insert();
//update();
delete();
}
}