1.导Jar包
获取Jar包:
2.给模块或项目添加依赖
3.加载驱动
// 类加载器加载jdbc驱动
Class.forName("com.mysql.cj.jdbc.Driver");
4.通过驱动管理进行链接数据库
// 驱动管理器创建通道 使用上转型赋值给 Connection
Connection conn = DriverManager.getConnection("jdbc:mysql:///fruitdb","root","123456");
6.使用Connection中的prepareStatement方法转载sql语句
// 创建Mysql语句格式代码 相当于包装
String sql = "insert into t_fruit values(null,?,?,?,?)";
// 使用通道进行运输sql 相当于货车
PreparedStatement psmt = conn.prepareStatement(sql);
7.使用PreparedStatement中的set***方法设置sql语句中?的参数
// 设置psmt中的sql格式代码的参数 将货物进行包装
psmt.setString(1,"苹果");
psmt.setInt(2,200);
psmt.setInt(3,200);
psmt.setString(4,"很好吃");
psmt.close();
conn.close();
8.调用PreparedStatement中的execute***方法 执行sql语句
| 函数名 | 作用 | 返回值 |
|---|---|---|
executeUpdate() |
执行增删改操作 | 返回受到影响的行数 |
executeQuery() |
执行查询操作 | ResultSet对象 |
int count = psmt.executeUpdate(); //返回更新行数
System.out.println(count > 0 ?"添加成功":"添加失败");
String sql = "select * from t_fruit";
PreparedStatement statement = connection.prepareStatement(sql); //返回查询结果
ResultSet rs = statement.executeQuery();
其中ResultSet相当于指针指向表头,调用next()函数执行向下移动一行,需要注意的是next()返回的是Boolean类型作用是判断是否存在下一行,再使用get***(Int) get***(String)函数用来分解ResultSet中的记录
注意
next()函数进行遍历查询结果
while (rs.next()) {
Integer pid = rs.getInt(1);
String fname = rs.getString(2);
Integer fcount = rs.getInt(3);
String remark = rs.getString("remark");
System.out.println(pid + fname + fcount + remark);
}
rs.close();
注意
/**
* Connection,PrepareStatement 的接口均为Sun公司规定的接口方便数据的开发
*/
DAO
Data Access Object 数据访问对象 , 声明此接口用于制定规则规范化操作,其实现类经常命名为为impl.***DaoImpl.class
//dao:Data Access Object 数据访问对象
//接口设计
public interface FruitDao {
String URL = "jdbc:mysql:///fruitdb";
String USER = "root";
String PSWORD = "123456";
void addFruit(Fruit fruit);
void delFruit(Fruit fruit);
void updateFruit(Fruit fruit);
List<Fruit> getFruitList();
Fruit getFruitByFname(String fname);
}
实现类
//设计实现方法
public class FruitDaoImpl implements FruitDao {
·····
}






没有回复内容