Druid
下载druid的jar包,粘贴到lib目录下,添加到库。
首先创建一个src目录下的配置文件druid.properties,写入以下信息:
driverClassName=com.mysql.cj.jdbc.Driver
username=root
password=root
url=jdbc:mysql:///atguigu
集体代码
package com.glut.api.druid;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Properties;
/**
* @author mhw
* @create 2023/3/5 15:54
* @email [email protected]
*/
public class DruidUsePart {
@Test
public void testSoft() throws Exception {
//1.读取外部配置文件
Properties properties = new Properties();
//src下的文件,可以使用类加载器下的方法
InputStream ips = DruidUsePart.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(ips);
//2.使用连接池的工具类的工程模式,创建连接池
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection connection = dataSource.getConnection();
//数据库操作
String sql = "insert into t_user (account,password,nickname) values(?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1,"test1");
preparedStatement.setObject(2,"test1");
preparedStatement.setObject(3,"二狗子1");
int rows = preparedStatement.executeUpdate();
if(rows>0){
System.out.println("插入成功");
}else{
System.out.println("插入失败");
}
preparedStatement.close();
connection.close();
}
}
标签:preparedStatement,java,sql,Druid,druid,使用,import,properties
From: https://www.cnblogs.com/ysfxt/p/17181427.html