java db 使用_JavaDB的基本使用[通俗易懂]

java db 使用_JavaDB的基本使用[通俗易懂]Derby並不是一個新的數據庫產品,它是由IBM捐獻給Apache的DB項目的一個純Java數據庫,JDK6.0里面帶的這個Derby的版本是10.2.1.7,支持存儲過程和觸發器;有兩種運行模式,一種是作為嵌入式數據庫,另一種是作為網絡數據庫,前者的數據庫服務器和客戶端都在同一個JVM里面運行,后者允許數據庫服務器端和客戶端不在同一個JVM里面,而且允許這兩者在不同的物理機器上.值得注意的是JD…

大家好,又见面了,我是你们的朋友全栈君。

Derby並不是一個新的數據庫產品,它是由IBM捐獻給Apache的DB項目的一個純Java數據庫,JDK6.0里面帶的這個Derby的版本是10.2.1.7,支持存儲過程和觸發器;有兩種運行模式,一種是作為嵌入式數據庫,另一種是作為網絡數據庫,前者的數據庫服務器和客戶端都在同一個JVM里面運行,后者允許數據庫服務器端和客戶端不在同一個JVM里面,而且允許這兩者在不同的物理機器上.值得注意的是JDK6里面的這個Derby支持JDK6的新特性JDBC 4.0規范(JSR 221),現在我們如果要練習JDBC的用法,沒有必要單獨裝一個數據庫產品了,直接用Derby就行.

下面是個使用derby的簡單例子:

首先導入JAR包:derby.jar,如果你裝的是JDK6,在C:/Program Files/Sun/JavaDB/lib目錄下就可以找到.

然后就要創建數據庫了:

Java代碼 aHR0cDovL2phcnJ5d2luLmphdmFleWUuY29tL2ltYWdlcy9pY29uX2NvcHkuZ2lm

privateConnection getConnection()throwsSQLException {

Connection connection = DriverManager

.getConnection(“jdbc:derby:userDB;create=true;user=test;password=test”);

connection.setAutoCommit(false);

returnconnection;

}private Connection getConnection() throws SQLException {

Connection connection = DriverManager

.getConnection(“jdbc:derby:userDB;create=true;user=test;password=test”);

connection.setAutoCommit(false);

return connection;

}

其中userDB是要連接數據庫的名字,create=true表示如果該數據庫不存在,則創建該數據庫,如果數據庫存在,則用用戶user=test;密碼password=test連接數據庫.

有了數據庫,接下來該建表了:

Java代碼 aHR0cDovL2phcnJ5d2luLmphdmFleWUuY29tL2ltYWdlcy9pY29uX2NvcHkuZ2lm

privatevoidcreateTable(Connection connection)throwsSQLException {

Statement statement = connection.createStatement();

String sql =”create table USERS(“

+”   ID                           BIGINT                       not null generated by default as identity,”

+”   USER_NAME            VARCHAR(20)            not null,”

+”   PASSWORD             VARCHAR(20),”

+”   constraint P_KEY_1 primary key (ID))”;

statement.execute(sql);

sql =”create unique index USER_NAME_INDEX on USERS (“

+”   USER_NAME            ASC)”;

statement.execute(sql);

statement.close();

}private void createTable(Connection connection) throws SQLException {

Statement statement = connection.createStatement();

String sql = “create table USERS(“

+ ” ID BIGINT not null generated by default as identity,”

+ ” USER_NAME VARCHAR(20) not null,”

+ ” PASSWORD VARCHAR(20),”

+ ” constraint P_KEY_1 primary key (ID))”;

statement.execute(sql);

sql = “create unique index USER_NAME_INDEX on USERS (“

+ ” USER_NAME ASC)”;

statement.execute(sql);

statement.close();

}

創建了USERS表,包括ID,USER_NAME,PASSWORD三個列,其中ID是主鍵,其中generated by default as identity的作用類似sequence,identity是定義自動加一的列,

GENERATED BY ALWAYS AS IDENTITY

GENERATED BY DEFAULT AS IDENTITY

By always和by default是說明生成這個IDENTITY的方式。

By always是完全由系統自動生成。

by default是可以由用戶來指定一個值。

編寫與USERS表對應的javabean(這個就不多說了),:

Java代碼 aHR0cDovL2phcnJ5d2luLmphdmFleWUuY29tL2ltYWdlcy9pY29uX2NvcHkuZ2lm

publicclassUserimplementsSerializable {

/**

*

*/

privatestaticfinallongserialVersionUID = 1L;

privateLong id;

privateString userName;

privateString password;

publicLong getId() {

returnid;

}

publicvoidsetId(Long id) {

this.id = id;

}

publicString getUserName() {

returnuserName;

}

publicvoidsetUserName(String userName) {

this.userName = userName;

}

publicString getPassword() {

returnpassword;

}

publicvoidsetPassword(String password) {

this.password = password;

}

}public class User implements Serializable {

/**

*

*/

private static final long serialVersionUID = 1L;

private Long id;

private String userName;

private String password;

public Long getId() {

return id;

}

public void setId(Long id) {

this.id = id;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

}

接下來就可以就數據庫進行增刪改查的操作了:

插入數據:

Java代碼 aHR0cDovL2phcnJ5d2luLmphdmFleWUuY29tL2ltYWdlcy9pY29uX2NvcHkuZ2lm

privatevoidcreate(User user) {

Connection connection =null;

try{

connection =this.getConnection();

PreparedStatement statement = connection

.prepareStatement(“insert into users (user_name,password) values(?,?)”);

intindex =1;

statement.setString(index++, user.getUserName());

statement.setString(index++, user.getPassword());

statement.execute();

user.setId(this.getId(connection));

connection.commit();

}catch(SQLException e) {

rollback(connection);

thrownewRuntimeException(e);

}finally{

if(connection !=null) {

close(connection);

}

}

}private void create(User user) {

Connection connection = null;

try {

connection = this.getConnection();

PreparedStatement statement = connection

.prepareStatement(“insert into users (user_name,password) values(?,?)”);

int index = 1;

statement.setString(index++, user.getUserName());

statement.setString(index++, user.getPassword());

statement.execute();

user.setId(this.getId(connection));

connection.commit();

} catch (SQLException e) {

rollback(connection);

throw new RuntimeException(e);

} finally {

if (connection != null) {

close(connection);

}

}

}

Java代碼 aHR0cDovL2phcnJ5d2luLmphdmFleWUuY29tL2ltYWdlcy9pY29uX2NvcHkuZ2lm

privateLong getId(Connection connection)throwsSQLException {

CallableStatement callableStatement = connection

.prepareCall(“values identity_val_local()”);

ResultSet resultSet = callableStatement.executeQuery();

resultSet.next();

Long id = resultSet.getLong(1);

resultSet.close();

callableStatement.close();

returnid;

}private Long getId(Connection connection) throws SQLException {

CallableStatement callableStatement = connection

.prepareCall(“values identity_val_local()”);

ResultSet resultSet = callableStatement.executeQuery();

resultSet.next();

Long id = resultSet.getLong(1);

resultSet.close();

callableStatement.close();

return id;

}

getId方法是獲得系統默認的id值,是通過identity_val_local()獲得的,而函數IDENTITY_VAL_LOCAL()則可以在INSERT語句執行之后,為我們返回剛才系統為id所產生的值.感覺還是有點想sequence的curr_val.

修改數據:

Java代碼 aHR0cDovL2phcnJ5d2luLmphdmFleWUuY29tL2ltYWdlcy9pY29uX2NvcHkuZ2lm

privatevoidupdate(User user) {

Connection connection =null;

try{

connection =this.getConnection();

PreparedStatement statement = connection

.prepareStatement(“update users set user_name=?,password=? where id=?”);

intindex =1;

statement.setString(index++, user.getUserName());

statement.setString(index++, user.getPassword());

statement.setLong(index++, user.getId());

statement.execute();

connection.commit();

}catch(SQLException e) {

rollback(connection);

thrownewRuntimeException(e);

}finally{

if(connection !=null) {

close(connection);

}

}

}private void update(User user) {

Connection connection = null;

try {

connection = this.getConnection();

PreparedStatement statement = connection

.prepareStatement(“update users set user_name=?,password=? where id=?”);

int index = 1;

statement.setString(index++, user.getUserName());

statement.setString(index++, user.getPassword());

statement.setLong(index++, user.getId());

statement.execute();

connection.commit();

} catch (SQLException e) {

rollback(connection);

throw new RuntimeException(e);

} finally {

if (connection != null) {

close(connection);

}

}

}

刪除數據:

Java代碼 aHR0cDovL2phcnJ5d2luLmphdmFleWUuY29tL2ltYWdlcy9pY29uX2NvcHkuZ2lm

publicvoiddelete(Long id) {

Connection connection =null;

try{

connection =this.getConnection();

PreparedStatement statement = connection

.prepareStatement(“delete from users where id=?”);

statement.setLong(1, id);

statement.execute();

connection.commit();

}catch(SQLException e) {

rollback(connection);

thrownewRuntimeException(e);

}finally{

if(connection !=null) {

close(connection);

}

}

}public void delete(Long id) {

Connection connection = null;

try {

connection = this.getConnection();

PreparedStatement statement = connection

.prepareStatement(“delete from users where id=?”);

statement.setLong(1, id);

statement.execute();

connection.commit();

} catch (SQLException e) {

rollback(connection);

throw new RuntimeException(e);

} finally {

if (connection != null) {

close(connection);

}

}

}

查詢數據:

Java代碼 aHR0cDovL2phcnJ5d2luLmphdmFleWUuY29tL2ltYWdlcy9pY29uX2NvcHkuZ2lm

publicUser findById(Long id) {

Connection connection =null;

try{

connection =this.getConnection();

PreparedStatement statement = connection

.prepareStatement(“select user_name,password from users where id=?”);

statement.setLong(1, id);

ResultSet resultSet = statement.executeQuery();

User user =null;

if(resultSet.next()) {

user =newUser();

user.setId(id);

user.setUserName(resultSet.getString(“user_name”));

user.setPassword(resultSet.getString(“password”));

}

resultSet.close();

statement.close();

connection.commit();

returnuser;

}catch(SQLException e) {

thrownewRuntimeException(e);

}finally{

if(connection !=null) {

close(connection);

}

}

}public User findById(Long id) {

Connection connection = null;

try {

connection = this.getConnection();

PreparedStatement statement = connection

.prepareStatement(“select user_name,password from users where id=?”);

statement.setLong(1, id);

ResultSet resultSet = statement.executeQuery();

User user = null;

if (resultSet.next()) {

user = new User();

user.setId(id);

user.setUserName(resultSet.getString(“user_name”));

user.setPassword(resultSet.getString(“password”));

}

resultSet.close();

statement.close();

connection.commit();

return user;

} catch (SQLException e) {

throw new RuntimeException(e);

} finally {

if (connection != null) {

close(connection);

}

}

}

以上就是derby的簡單操作.

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/156460.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 测试显卡矿卡用什么软件,3分钟看懂:AMD二手矿卡简明鉴别、检测教程,从此脱坑不求人…「建议收藏」

    测试显卡矿卡用什么软件,3分钟看懂:AMD二手矿卡简明鉴别、检测教程,从此脱坑不求人…「建议收藏」3分钟看懂:AMD二手矿卡简明鉴别、检测教程,从此脱坑不求人2020-03-2700:10:00135点赞716收藏90评论创作立场声明:Tony哥的矿卡日记二手矿卡坑太深,手握秘籍不求人AMD自2016年中发布Polaris系列GPU至今,长达四年的时间里,一代又一代的RX470、480、570、580等显示卡进入暗无天日的区块链矿场,挥洒着血泪和青春。在经历一次次矿难之后,貌似廉价的二手矿卡…

    2022年6月5日
    692
  • RTMP协议

    目录简介概念rtmp协议握手过程rtmp通信过程简介RTMP协议是RealTimeMessageProtocol(实时信息传输协议)的缩写,它是由Adobe公司提出的一种应用层的协议,用来解决多媒体数据传输流的多路复用(Multiplexing)和分包(packetizing)的问题。     RTMP消息块流和RTMP一起适用于多样性音视频应用程序,从…

    2022年4月3日
    189
  • cdma是第几代移动通信系统_移动通信系统的双工分为

    cdma是第几代移动通信系统_移动通信系统的双工分为第三代移动通信系统旨在提供包括卫星在内的全球覆盖并实现有线和无线以及不同无线网络之间业务的无缝连接,同时针对不同的业务应用,提供从9.6kbit/s~2Mbit/s的接入速率,满足多媒体业务的要求。国际电联(ITU)把第三代移动通信系统称为IMT-2000。第三代移动通信系统主流的技术标准有WCDMA、TD-SCDMA、CDMA2000。WCDMA主要技术指标和特点WCDMA核心网络基于GSM/GPRS网络的演进,保持与GSM/GPRS网络的兼容性;核心网络可以基于TDM、ATM和

    2022年10月3日
    0
  • C++简单有趣的恶搞问答关机程序

    C++简单有趣的恶搞问答关机程序点进来的朋友首先反思一下自己:为什么进了CSDN这样一个学习的社区却还要来看我这种无聊的额恶搞程序呢?哈哈!我来替你们回答吧——因为无聊呗!没错,我也是无聊,五一假期显得无聊,看到高中班群实在安静决定写个小程序恶搞一下班级同学。闲话不多说,先来看一下效果吧!当你的同学收到.exe的可执行文件之后双击,首先他看到的是这样的界面:好吧,看到题目一句一句的跳出,如果你是我同学,估计你也应该开始…

    2022年7月22日
    19
  • 随机森林随机选择特征的方法_随机森林步骤

    随机森林随机选择特征的方法_随机森林步骤当你读到这篇博客,那么你肯定知道手动调参是多么的低效。那么现在我来整理一下近几日学习的笔记,和大家一起分享学习这个知识点。

    2022年8月30日
    1
  • 零基础学Java难不难?

    零基础学Java难不难?很多同学在学Java前都会问零基础能学Java吗?Java到底难不难学?本文我就和大家唠唠这个事。有74%的人认为不难,说难学的仅占26%。

    2022年7月7日
    63

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号