1.导入第三方的类
导包步骤: 右键project->property->java build path->libaries->add external jars
通过Class.forName("com.mysql.jdbc.Driver");
初始化驱动类:com.mysql.jdbc.Driver
2.建立与数据库的Connection连接 这里需要提供: 数据库所处于的ip:127.0.0.1 (本机)数据库的端口号: 3306 (mysql专用端口号)数据库名称 HelloWorld编码方式 UTF-8账号 root密码 admin
Connection c = DriverManger.getConnection("jdbc:mysql://127.0.0.1:3306/HelloWorld?characterEncoding = UTF-8 ", "root","admin");
3.创建Statement是用于执行SQL语句,比如增加,删除
Statement s = c.createStatement();
4.执行SQL语句
执行SQL语句之前要确保数据库HelloWorld中有表hero的存在,如果没有,需要事先
String sql = "insert into hero values(null,"+" '提莫' "+","+313.0f+","+50+")";
s.execute(sql);
5.关闭连接
先关闭Statement
后关闭Connection
6.使用try-with-resource的方式自动关闭连接
例如:try(...){...}catch(...){...}
二、CRUD(增删改查)
例子:
增
String sql =
"insert into hero values(null,"
+
"'提莫'"
+
","
+
313
.0f +
","
+
50
+
")"
;
删
String sql =
"delete from hero where id = 5"
;
改
String sql =
"update hero set name = 'name 5' where id = 3"
;
查
String sql =
"select * from hero"
;
// 执行查询语句,并把结果集返回给ResultSet
ResultSet rs = s.executeQuery(sql);
while
(rs.next()) {
int
id = rs.getInt(
"id"
);
// 可以使用字段名
String name = rs.getString(
2
);
// 也可以使用字段的顺序
float
hp = rs.getFloat(
"hp"
);
int
damage = rs.getInt(
4
);
System.out.printf(
"%d\t%s\t%f\t%d%n"
, id, name, hp, damage);
}
获取总数:
String sql =
"select count(*) from hero"
;