JDBC
Connection 接口、Statement 接口、PreapredStatement 接口、ResultSet 接口、DriverManager 类
.properties 配置文件的用法
Properties pro = new Properties();
pro.load(JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
driverClass = pro.getProperty("driverClass");
username = pro.getProperty("username");
password = pro.getProperty("password");
url = pro.getProperty("url");
database = pro.getProperty("database");
JDBC连接数据库和操作
Statement 接口和ResultSet 接口 直接字符串拼接
//1.注册驱动---获取Driver类的全部信息,driverClass=com.mysql.jdbc.Driver 在配置文件写好
Class.forName(driverClass);
//2.获取数据库连接
Connection conn = DriverManager.getConnection(url+database, username, password);
//3.获取 Statement 对象
Statement st = conn.createStatement();
//返回表数据
//1.ResultSet 接受查询结果
ResultSet rs = st.executeQuery("select * from student");//返回集合,遍历rs.next()获得信息
//2.Statement接口对数据库更新,插入,删除操作
String sql = "sql语句";//插入INSERT,UPDATA更新,删除DELETE
st.executeUpdate(sql);//返回作用的行数
CloseUtil.closeAll(st,rs,conn);//关闭流
PreapredStatement 接口 预处理,安全
PreapredStatement插入数据
String name = "Mr'Smith";
String sex = "中";
String birthday = "1990-02-14";
float salary = 90.0f;
String sql = "INSERT INTO person(pid,name,sex,birthday,salary) " + "VALUES (1,?,?,?,?)";
// 1、加载数据库驱动程序
Class.forName(DBDRIVER);
// 2、数据库连接
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
// 3.实例化PreparedStatement对象
pstmt = conn.prepareStatement(sql);
/* 预处理数据 */
pstmt.setString(1, name);
pstmt.setString(2, sex);
pstmt.setDate(3, new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd") .parse(birthday).getTime()));
pstmt.setFloat(4, salary);
pstmt.executeUpdate(); //提交信息
// 4、关闭
pstmt.close();
conn.close();
prepareStatement查询数据
// 1、加载数据库驱动程序
Class.forName(DBDRIVER);
// 2、数据库连接
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
//pstmt = conn.createStatement(sql) ;上面用这个
pstmt = conn.prepareStatement(sql) ;
String sql = "SELECT pid,name,sex,birthday,salary FROM person";
rs = pstmt.executeQuery(sql);// 执行查询操作
while (rs.next()) {
int pid = rs.getInt(1);
String name = rs.getString(2);
String sex = rs.getString(3);
Date date = rs.getDate(4);
float salary = rs.getFloat(5);
System.out.println("编号:" + pid + ",姓名:" + name + ",性别:" + sex + ",生日:" + date + ",工资:" + salary);
}
// 3、关闭
CloseUtil.closeAll(rs,pstmtconn);
要连接Mysql导入包
在eclipse建个package aa
把jar包用鼠标拉进去
右键jar包–>Bulid path–>Add to Bulid Path
完成