JDCB连接mysql与增删改查基本操作

JDCB连接连接数据库与JDBC连接、增删改、查询的通用方法

JDCB连接连接MySQL数据库的几种方式(异常建议try catch 处理,这里只说明连接方式,都throw处理):

第一种方式

package test1;
import org.junit.Test;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;
public class Test1 {
    @Test
    public void test1() throws SQLException {
    // 获取驱动实例
        Driver driver =new com.mysql.jdbc.Driver();
    //url       协议://ip:端口号/数据库
        String url="jdbc:mysql://localhost:3306/test";
    //数据库连接信息(用户名密码)封装到Properties对象中
        Properties info = new Properties();
   		info.setProperty("user","root");
        info.setProperty("password","123456");

    //获取数据库连接
        Connection conn = driver.connect(url, info);
        System.out.println(conn);
    }
}

第二种方式:

@Test
public void test2() throws Exception {
    //反射
    Class clazz = Class.forName("com.mysql.jdbc.Driver");
    Driver driver = (Driver) clazz.newInstance();

    String url="jdbc:mysql://localhost:3306/test";
    //数据库连接信息(用户名密码)封装到Properties对象中
    Properties info = new Properties();
    info.setProperty("user","root");
    info.setProperty("password","123456");

    //获取数据库连接
    Connection conn = driver.connect(url, info);
    System.out.println(conn);
}

第三种方式:

@Test
public  void test3() throws Exception{
    //提供数据库连接信息
    String url="jdbc:mysql://localhost:3306/test";
    String user = "root";
    String password = "123456";

    //使用反射获取Driver接口的实现类对象
    Class clazz = Class.forName("com.mysql.jdbc.Driver");
    Driver driver = (Driver) clazz.newInstance();//可省略

    //提供数据库连接信息
    String url="jdbc:mysql://localhost:3306/test";
    String user = "root";
    String password = "123456";

    //注册驱动
    DriverManager.registerDriver(driver);//可省略

    //使用DriverManager获取数据库连接
    Connection conn = DriverManager.getConnection(url, user, password);
    System.out.println(conn);
}

第四种方式(推荐):

@Test
public void test() throws Exception {
    InputStream is = Test1.class.getClassLoader().getResourceAsStream("jdbc.properties");
    Properties pros= new Properties();
    pros.load(is);

    String user = pros.getProperty("user");
    String password = pros.getProperty("password");
    String url = pros.getProperty("url");
    String driverClass = pros.getProperty("driverClass");

    Class.forName(driverClass);
    Connection conn = DriverManager.getConnection(url,user,password);
    System.out.println(conn);
}

>
通用的数据库连接、关闭方法

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
	
	//获取数据库连接的通用方法
	public static Connection getConnection() throws Exception {
		// 1.读取配置文件中的4个基本信息,配置文件内容见文章底部
		InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");

		Properties pros = new Properties();
		pros.load(is);

		String user = pros.getProperty("user");
		String password = pros.getProperty("password");
		String url = pros.getProperty("url");
		String driverClass = pros.getProperty("driverClass");

		// 2.加载驱动
		Class.forName(driverClass);

		// 3.获取连接
		Connection conn = DriverManager.getConnection(url, user, password);
		return conn;
	}
	
	// 关闭连接和Statement的操作的方法
	public static void closeResource(Connection conn,Statement ps){
		try {
			if(ps != null)
				ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(conn != null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	//关闭资源操作
	public static void closeResource(Connection conn,Statement ps,ResultSet rs){
		try {
			if(ps != null)
				ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(conn != null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

>
通用的增删改操作:

public void update(String sql,Object ...args){//sql中占位符的个数与可变形参的长度相同!
	Connection conn = null;
	PreparedStatement ps = null;
	try {
		//1.获取数据库的连接
		conn = JDBCUtils.getConnection();
		//2.预编译sql语句,返回PreparedStatement的实例
		ps = conn.prepareStatement(sql);
		//3.填充占位符
		for(int i = 0;i < args.length;i++){
			ps.setObject(i + 1, args[i]);//小心参数声明错误!!
		}
		//4.执行
		ps.execute();
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		//5.资源的关闭
		JDBCUtils.closeResource(conn, ps);
	}
}

>
通用的查询操作:

	public <T> List<T> getForList(Class<T> clazz,String sql, Object... args){
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JDBCUtils.getConnection();

			ps = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}

			rs = ps.executeQuery();
			// 获取结果集的元数据 :ResultSetMetaData
			ResultSetMetaData rsmd = rs.getMetaData();
			// 通过ResultSetMetaData获取结果集中的列数
			int columnCount = rsmd.getColumnCount();
			//创建集合对象
			ArrayList<T> list = new ArrayList<T>();
			while (rs.next()) {
				T t = clazz.newInstance();
				// 处理结果集一行数据中的每一个列:给t对象指定的属性赋值
				for (int i = 0; i < columnCount; i++) {
					// 获取列值
					Object columValue = rs.getObject(i + 1);

					// 获取每个列的列名
					// String columnName = rsmd.getColumnName(i + 1);
					String columnLabel = rsmd.getColumnLabel(i + 1);

					// 给t对象指定的columnName属性,赋值为columValue:通过反射
					Field field = clazz.getDeclaredField(columnLabel);
					field.setAccessible(true);
					field.set(t, columValue);
				}
				list.add(t);
			}
			
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.closeResource(conn, ps, rs);

		}

		return null;
	}

>
Properties文件内容

#数据库地址
url=jdbc:mysql://localhost:3306/jdbc
#用户名密码
user=root
password=123456
#mysql驱动
driverClass=com.mysql.jdbc.Driver

你可能感兴趣的:(java)