建立一个 Derby 日历,第 1 部分: 理解 JDBC
2010-04-19 00:00:00 来源:WEB开发网让我们从底部的 main() 方法开始。为使事情尽可能简单(因为 main() 方法的最终目的仅仅是用来测试我们的功能),只把信息作为参数接受。在把信息从 args 数组中提取出来之后,创建 Event 对象。
然后,构造器调用 create() 方法,它仅仅显示信息,如 清单 7 所示。
清单 7.从 create() 方法显示的信息
C:\>java Event
Usage: Event <title> <description> <remindersTo> <month> <day> <year>
C:\>java Event
"Going to New Jersey"
"Bring up dad's bubble gum machines in the car."
"questions@nicholaschase.com" 8 25 2005
Creating event for 8/25/2005
Going to New Jersey
Bring up dad's bubble gum machines in the car.
现在,让我们来看看添加信息到数据库。
连接到数据库
第一步,创建一个到数据库的连接,如 清单 8 所示。
清单 8.连接到数据库
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
public class Event {
public String driver =
"org.apache.derby.jdbc.EmbeddedDriver";
public Event(){}
...
public boolean create(String newTitle, String newDescription,
String newRemindersTo, int eventMonth,
int eventDay, int eventYear) {
setTitle(newTitle);
setDescription(newDescription);
setRemindersTo(newRemindersTo);
setEventMonth(eventMonth);
setEventDay(eventDay);
setEventYear(eventYear);
System.out.println("Creating event for " + this.getEventMonth()+
"/" + this.getEventDay() + "/" +
this.getEventYear());
System.out.println(this.getTitle());
System.out.println(this.getDescription());
System.out.println("Reminders to: " + this.getRemindersTo());
try {
Class.forName(driver).newInstance();
Connection conn = null;
conn = DriverManager.getConnection(
"jdbc:derby:c:\\derby\\calendar");
conn.setAutoCommit(true);
conn.close();
} catch (Exception e){
e.printStackTrace();
return false;
}
return true;
}
...
更多精彩
赞助商链接