前段时间学习了jdbc,正好利用这几篇文章总结一下。
JDBC 可做三件事:与数据库建立连接、发送操作数据库的语句并处理结果。
而程序首先要做的就是加载数据库驱动,这里我使用的是mysql:
String driverName=new String("com.mysql.jdbc.Driver");
Class.forName(driverName);
String url=new String("jdbc:mysql://localhost:3306/jdbc");
String user=new String("root");
String password=new String("123456");
Connection coon=DriverManager.getConnection(url, user, password);
因为要对数据库进行操作,所以要获取Statement对象:
Statement statement = connection.createStatement();
String sql = null;
ResultSet resultSe = nullt;
//创建Student表
sql="create table Student (id char(9) primary key,name char(9) unique)";
statement.execute(sql);
//添加元组
sql = "insert into Student (id,name) values ('0001','zhangsan')";
statement.executeUpdate(sql);
//查询Student表
sql="select * from Student";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("name:"+resultSet.getString("name"));
System.out.println("id:"+resultSet.getString("id"));
}
//删除元组
sql="delete from Student where id='0001'";
statement.executeUpdate(sql);
//删除表Student
sql="drop table Teacher";
statement.execute(sql);
操作完数据库之后要关闭资源,顺序依次为resultSet,statement,connection:
try {
if (resultSet != null)
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
resultSet = null;
try {
if (statement != null)
statement.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
statement = null;
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
connection = null;
}
}
}