JDBC连接数据库
在此之前先导包
代码如下(记得在数据库里建表)
新建一个空文件
可以命名为druid.properties并且将下面的代码输入进去
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root
以下开始连接
package Utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* Druid连接池的工具类
*/
public class jdbcutil {
private static DataSource ds;
static {
try {
//1.加载配置文件
//ClassLoader类加载器
//类名。class。传一个文件命 回去其路径
Properties pro = new Properties();
pro.load(jdbcutil.class.getClassLoader().getResourceAsStream("druid.properties"));
//2.获取DataSource
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//释放资源
public static void close(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Statement stmt, Connection conn) {
close(null, stmt, conn);
}
//获取连接池的方法
public static DataSource getDataSource() {
return ds;
}
}
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import Utils.jdbcutil;
public class jdbctemplate {
private JdbcTemplate template = new JdbcTemplate(jdbcutil.getDataSource());
public void test1() {
//1获取jdbctemplate
String sql = "update chengji set grade = '111'where id = 1";
int update = template.update(sql);
System.out.println(update);
}
@Test
public void test5() {
String sql = "select * from user"; //查询数据库的表user
List a = template.queryForList(sql);
System.out.println( );
Iterator it = a.iterator();
while (it.hasNext()){
Map b= (Map) it.next(); //使用map集合输出表的属性
System.out.print(b.get("id"));
System.out.print(b.get("name"));
System.out.println(b.get("pwd"));
}
}
}
补充: 修改表 这里修改表用户的密码
@Test
public void test6() {
String sql="update user set pwd=? where name=?";
int n=template.update(sql,new Object[]{56,"123"});
}
运行了tes6 成功后运行test5 观察修改成功