19、Java数据库编程:
JDBC概述:
JDBC(Java Database Connection)是java中提供的一套数据库编程API,它定义了一套用来访问数据库的标准Java类库(位于java.sql和javax.sql)。
JDBC对于开发人员而言是API,对于厂商而言作为借口。
JDBC编程步骤:
1.(Driver)根据应用程序所用的数据库,选择JDBC驱动程序类型。
2.链接到数据库,得到Connection对象。
3.通过Connection创建Statemenet对象。
4.使用Statemnet对象提交SQL语句。
5.操作结果集。
6.回收数据库资源。
public class TestMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// 加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 通过驱动管理器获取数据库连接
Connection con = null;
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "");
// 增加操作
StudentBean stu = new StudentBean("叶娟", 18, "女", "LOVO教育");
String sql = "insert into t_student(f_name,f_age,f_gender,f_school) values('" + stu.getName()
+ "'," + stu.getAge() + ",'" + stu.getGender() + "','"
+ stu.getSchool() + "')";
//使用连接创建语句对象
Statement state = con.createStatement();
int result = state.executeUpdate(sql);
System.out.println(result);
//修改操作
String sql = "update t_student set f_name = '田姐' where pk_id = 2";
String sql = "update t_student set f_school = '中国Lovo'";
Statement state = con.createStatement();
int result = state.executeUpdate(sql);
System.out.println(result);
//删除操作与修改完全一样,只是SQL语句不同
//查询
ArrayList<StudentBean> allStu = new ArrayList<StudentBean>();
String sql = "select * from t_student";
Statement state = con.createStatement();
ResultSet rs = state.executeQuery(sql);
while(rs.next()){
//下标是从1开始
int id = rs.getInt(1);
String name = rs.getString(2);
int age = rs.getInt(3);
String gender = rs.getString(4);
String school = rs.getString(5);
int id = rs.getInt("id");
String name = rs.getString("f_name");
int age = rs.getInt("f_age");
String gender = rs.getString("f_gender");
String school = rs.getString("f_school");
allStu.add(new StudentBean());
System.out.println(id + " " + name + " " + age + " " + gender + " " + school);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}