package com.chenzebin.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCTest {
/**
*
* @Title: getConnection
* @Description: 获取数据库连接
* @param @return
* @return Connection 返回类型
* @throws
*/
public static Connection getConnection() {
Connection conn = null;
try {
// 注册mysql的jdbc的驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 连接数据库
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root", "");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return conn;
}
/**
*
* @Title: insert
* @Description: 向数据库插入数据
* @param
* @return void 返回类型
* @throws
*/
public static void insert() {
Connection conn = getConnection();
try {
String sql = "insert into tbl_user(name,password,email)" + "values('Tom','123456','tom@gmail.com')";
// 这个Statement一定要用conn开创建,因为conn连接数据库,所以它创建的Statement才有权限对这个数据库进行操作
Statement st = conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println("向用户表中插入" + count + "条记录");
conn.close();// 关闭数据库连接
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
*
* @Title: update
* @Description: 向数据库更新数据
* @param
* @return void 返回类型
* @throws
*/
public static void update() {
Connection conn = getConnection();
try {
String sql = "update tbl_user set email = 'tom@126.com' where name = 'Tom'";
Statement st = conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println("向用户表中更新了" + count + "条记录");
conn.close();// 关闭数据库连接
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
*
* @Title: delete
* @Description: 向数据库删除数据
* @param
* @return void 返回类型
* @throws
*/
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) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void main(String[] args) {
// insert();
// update();
delete();
}
}
网友评论