您的位置:首页 > 数据库 > MySQL

jdbc基础 (一) MySQL的简单使用

2015-05-12 16:07 375 查看
前段时间学习了jdbc,正好利用这几篇文章总结一下。

JDBC 可做三件事:与数据库建立连接、发送操作数据库的语句并处理结果。

而程序首先要做的就是加载数据库驱动,这里我使用的是mysql:

String driverName=new String("com.mysql.jdbc.Driver");
Class.forName(driverName);


然后再获取数据库连接对象,参数为数据库的url,用户名以及密码。这里我使用的数据库名为jdbc,用户名为root,密码为123456:
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();


statement对象内封装的execute(String sql)方法以及executeQuery(String sql)方法和executeUpdate(String sql)方法可以用来执行sql语句,以此来实现对数据库的操作。
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;
}
}
}


close()方法会抛出异常,需要try/catch语句块。为保证资源的释放,需要将close()方法的调用放在finally语句块里,释放资源前判断对象是否为null。至此,利用jdbc连接数据库进行简单的操作算是完成了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: