如何使小应用程序连接到MS Access数据库?
问题描述:
编写一个小程序,其中显示 接口,用于下面描述的程序 。当小程序执行时, 将在 适当的布局中显示屏幕,并响应 用户的操作。如何使小应用程序连接到MS Access数据库?
该程序模拟具有以下 特色的学生 管理系统:
的接口是有吸引力的,非常用户 友好,直观的(即充当 有人希望它采取行动),并 合理现实。它必须接受 用户的姓名,年龄,地址,日期 用户的姓名,性别,血型等,并将其保存在MS Access 数据库中。 +电子邮件ID,电话号码,级别。
该接口使用命令按钮 (I)添加,编辑,删除,更新和取消 的记录,(ii)向前进导航 记录或向后(ⅲ)至 移动直接到第一记录或最后 记录。当用户按下 “报告”按钮时,应使用 报告显示输入的记录数量 。
最初使所有字段不可见 或变灰。
在界面中适当使用 至少有一组“单选按钮”和 至少有一个“下拉列表”。使 管理员适当使用布局 。
答
您可以通过将MS-Access数据库添加到您的ODBC源中来访问它。
要打开数据源(ODBC),单击开始,单击控制面板,然后单击性能和维护。单击管理工具,然后双击数据源(ODBC)。
下面是一些您可以熟悉的示例代码。看看java.sql.*相关的类和方法 - 您几乎可以找到所有与数据库交互的答案。是的,在这里进行的视觉摇摆类有一些可怕的耦合(你应该抛出一个错误,而不是只显示一个并强制系统退出)。另外,我认为也不赞成使用JdbcOdbcDriver。
import javax.swing.*;
import sun.jdbc.odbc.JdbcOdbcDriver;
import java.sql.*;
import java.util.*;
public class SalesDB
{
private static Connection connect;
/**
* Connects to the database. This method must be run before any of the other methods since
* this method enables the connection to the database.
*/
public static void connect()
{
//The 'a5q3db' is the name of the ODBC source that you added.
String url = "jdbc:odbc:a5q3db";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connect = DriverManager.getConnection(url);
}
catch (ClassNotFoundException ex)
{
JOptionPane.showMessageDialog(null, "Failed to load JDBC/ODBC driver. Program will now terminate.");
System.exit(-1);
}
catch (SQLException ex)
{
JOptionPane.showMessageDialog(null, "Failed to connect to the database. Program will now terminate.");
System.exit(-1);
}
}
/**
* close the database connection before the program terminates.
*/
public static void close()
{
try
{
connect.close();
}
catch (SQLException ex)
{
}
}
/**
* Runs the supplied string as a query to the database and returns the result set.
* @param query The query with which to execute to the database.
* @return The generated resultset from java.sql.Statement#executeQuery(String).
*/
public static ResultSet runQuery (String query)
{
ResultSet result;
try
{
Statement statement = connect.createStatement();
result = statement.executeQuery(query);
}
catch (SQLException ex)
{
return null;
}
return result;
}
}//End SalesDB class.
好的,你到底在哪一步?这是感兴趣的问题。 – BalusC 2010-11-04 02:08:27
发布你已经做了什么。 – clyc 2010-11-04 02:13:11
请遵循[general](http://tinyurl.com/so-hints)问题[准则](http://meta.stackexchange.com/q/10812),陈述任何特殊的限制,显示你所尝试过的到目前为止,并询问具体是什么令你困惑。 – 2010-11-10 03:57:01