Java 读取数据库的jdbc配置

import java.awt.List;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;


import org.junit.Test;


public class Demo1 {


String url = "jdbc:mysql://localhost:3306/day15?characterEncoding=utf8";
private String user = "root";
private String password = "root";


// jdbc协议:数据库子协议:主机:端口/连接的数据库//
/*
* Driver 包
*/
@Test
public void test2() throws Exception {
Statement statement = null;
Connection connection = null;
try {
// 用驱动管理连接数据库
// Driver driver=new com.mysql.jdbc.Driver(); //新版本的
// 通过字节码的方式加载静态代码块,从而注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 注册一个驱动程序
// DriverManager.registerDriver(driver);
// 连接数据库
connection = DriverManager.getConnection(url, user, password);
// 准备sql语句


/* 创建表 */
// String
// sql="CREATE TABLE student(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),gender VARCHAR(2));";


/* 插入记录 */
// String sql="INSERT INTO student(NAME,gender) VALUES('张三','男');";


/* 更新 */
// String sql="UPDATE student SET NAME='王五' WHERE id=5;";


/* 删除 */
String sql = "DELETE FROM student WHERE id=6;";


// 创建 statement对象
statement = connection.createStatement();


// 执行
int count = statement.executeUpdate(sql);


System.out.println("影响的行数为" + count);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException();
} finally {
// 后打开先关闭
if (statement != null) {
try {
statement.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException();
}
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException();
}
}
}
}


/*
* 查询
*/
@Test
public void test3() {
Connection conn = null;
Statement statement = null;
ResultSet reSet = null;
try {
// 获取连接对象
conn = jdbcUtil.getConnection();
// 创建statement对象
statement = conn.createStatement();
// 查询sql语句
String sql = "SELECT * FROM student;";
// 读取数据
reSet = statement.executeQuery(sql);
java.util.List<Student> list = new ArrayList<Student>();
while (reSet.next()) {
Student stu = new Student();
stu.setId(reSet.getInt("id"));
stu.setName(reSet.getString("name"));
stu.setGender(reSet.getString("gender"));
list.add(stu);
}
for (Student stu : list) {
System.out.println(stu.getId());
System.out.println(stu.getName());
System.out.println(stu.getGender());
}
} catch (Exception e) {
jdbcUtil.close(conn, statement, reSet);
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值