如何使用JDBC程序连接到Derby数据库?
Apache Derby是一个关系数据库管理系统,它完全基于Java编程语言(以Java编程语言编写/实现)。它是由Apache Software Foundation开发的开源数据库。
安装derby:
请按照下面给出的步骤安装derby:
访问Apache Derby主页https://db.apache.org/derby/的主页。单击下载选项卡。
选择并单击最新版本的Apache Derby的链接。
单击所选链接后,您将被重定向到apache derby的“分发”页面。如果您在此处观察到,则derby提供的发行版分别是db-derby-bin,db-derbylib.zip,db-derby-lib-debug.zip和db-derby-src.zip。
下载db-derby-bin文件夹。将其内容复制到要安装Apache Derby的单独文件夹中。(例如,说C:\ Derby)
现在,要与Derby合作,
通过传递Java安装文件夹中bin文件夹的位置,确保已设置JAVA_HOME变量,并将JAVA_HOME / bin包含在PATH变量中。
创建一个新的环境变量DERBY_HOME,其值为C:\ Derby。
db-derby-bin发行版的bin文件夹(我们将其更改为C:\ Derby \ bin)包含所有必需的jar文件。
示例
接下来的JDBC程序建立与Apache derby数据库的连接,创建一个名为employeedata的表,在其中插入记录,检索并显示表的内容。
public class InsertData {public static void main(String args[]) throws Exception {
//注册驱动程序
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//获取连接对象
String URL = "jdbc:derby:mydatabs;create=true";
Connection conn = DriverManager.getConnection(URL);
//创建Statement对象
Statement stmt = conn.createStatement();
//在Derby数据库中创建表
String query = "CREATE TABLE EmployeeData( "
+ "Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, "
+ "Name VARCHAR(255), "
+ "Salary INT NOT NULL, "
+ "Location VARCHAR(255), "
+ "PRIMARY KEY (Id))";
stmt.execute(query);
System.out.println("Table created");
//插入数据
query = "INSERT INTO EmployeeData("
+ "Name, Salary, Location) VALUES "
+ "('Amit', 30000, 'Hyderabad'), "
+ "('Kalyan', 40000, 'Vishakhapatnam'), "
+ "('Renuka', 50000, 'Delhi'), "
+ "('Archana', 15000, 'Mumbai'), "
+ "('Trupthi', 45000, 'Kochin'), "
+ "('Suchatra', 33000, 'Pune'), "
+ "('Rahul', 39000, 'Lucknow'), "
+ "('Trupthi', 45000, 'Kochin')";
stmt.execute(query);
System.out.println("Values inserted");
//检索数据
ResultSet rs = stmt.executeQuery("Select * from EmployeeData");
System.out.println("表EmployeeData表的内容:");
while(rs.next()) {
System.out.print("ID: "+rs.getInt("ID")+", ");
System.out.print("Name: "+rs.getString("Name")+", ");
System.out.print("Salary: "+rs.getInt("Salary")+", ");
System.out.print("Location: "+rs.getString("Location"));
System.out.println();
}
}
}
输出结果
Table createdValues inserted
表EmployeeData表的内容:
ID: 1, Name: Amit, Salary: 30000, Location: Hyderabad
ID: 2, Name: Kalyan, Salary: 40000, Location: Vishakhapatnam
ID: 3, Name: Renuka, Salary: 50000, Location: Delhi
ID: 4, Name: Archana, Salary: 15000, Location: Mumbai
ID: 5, Name: Trupthi, Salary: 45000, Location: Kochin
ID: 6, Name: Suchatra, Salary: 33000, Location: Pune
ID: 7, Name: Rahul, Salary: 39000, Location: Lucknow
ID: 8, Name: Trupthi, Salary: 45000, Location: Kochin
以上是 如何使用JDBC程序连接到Derby数据库? 的全部内容, 来源链接: utcz.com/z/349184.html