一、如何使用Mysql-JDBC
1、导包
最后找到mysql的jar包
二、开始使用
第一步:连接数据库
可以自定义一个类,以下通过代码体现
package mysql.util;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class MysqlUtil {
static String DRIVER;
static String URL;
static String USER;
static String PASSWD;
static Connection connection = null;
static PreparedStatement ps = null;
static ResultSet rs = null;
//获取连接操作mysql
static{
try {
//获取配置文件对象
Properties properties = new Properties();
//通过反射操作配置文件加载到当前类中 MysqlUtil.class
InputStream rs = MysqlUtil.class.getClassLoader().getResourceAsStream("mysql.properties");
properties.load(rs);
DRIVER = properties.getProperty("DRIVER");
URL = properties.getProperty("URL");
USER = properties.getProperty("USER");
PASSWD = properties.getProperty("PASSWD");
Class.forName(DRIVER);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection(){
try {
connection = DriverManager.getConnection(URL, USER, PASSWD);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//获取执行器
public static PreparedStatement getPrepareStatement(String sql){
try {
ps = connection.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return ps;
}
//执行sql 查功能
public static ResultSet getSelect(){
try {
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
//执行sql 增删改功能
public static int getInsert(){
int i = 0;
try {
i = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return i ;
}
public static void close(){
if (ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
三、具体使用工具类实现操作mysql数据库的代码(通过类名调用相应的方法)
public static void main(String[] args) {
MysqlUtil.getConnection();
//增
// String sql = "insert into user(username,passwd) values('show','show')";
//删
String sql = "delete from user where username='show'";
MysqlUtil.getPrepareStatement(sql);
int insert = MysqlUtil.getInsert();
System.out.println(insert);
MysqlUtil.close();
}