[原创]作业:家庭消费管理程序,一点代码
最后的图:
操作数据库的 DBconn.cs:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
//数据类
namespace winfamily
{
class DBconn
{
private OleDbConnection conn;
//属性
public OleDbConnection Conn
{
get { return conn; }
}
//连接数据库
public DBconn(string sql)
{
conn = new OleDbConnection(sql);
}
//取得数据集
public DataSet getdb(string str)
{
Conn.Open();
OleDbDataAdapter oleda;
oleda = new OleDbDataAdapter(str,Conn);
DataSet ds = new DataSet();
oleda.Fill(ds);
//关闭
Conn.Close();
return ds;
}
}
}
------------------------------------------
应用程序的配置文件: App.conifg:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="sql" value="provider=Microsoft.Jet.OLEDB.4.0;data source=db.mdb"/>
</appSettings>
</configuration>
---------------------------
提交消费信息的代码(当然,最好使用参数插入到数据库):
//提交消费信息到数据库
private void button1_Click(object sender, EventArgs e)
{
//得到数据库 表需要的数据
string time = xfDatetime.Text;
string type = xfType.SelectedItem.ToString();
double money =double.Parse(xfMoney.Text);
string address = xfAddress.Text;
string person = xfPerson.Text;
string info = xfInfo.Text;
//插入数据
string str = "insert into expenditure(消费日期,消费类别,消费金额,消费地点,消费者,备注说明) " +
"values(#" + time + "#,'" + type + "'," + money + ",'" + address + "','" + person + "','" + info + "')";
//执行SQL操作
DBconn dbClass = new DBconn(sql);
OleDbCommand command = new OleDbCommand(str, dbClass.Conn);
dbClass.Conn.Open();
command.ExecuteNonQuery();
dbClass.Conn.Close();
MessageBox.Show("提交成功!");
}
---------
查询消费信息的代码:
//查询信息
private void button2_Click(object sender, EventArgs e)
{
//查询语句
string str = "select * from expenditure ";
if (cxType.SelectedItem.ToString().Trim() != "")
str += "where 消费类别='" + cxType.SelectedItem.ToString()+"'";
if (cxperson.SelectedItem.ToString().Trim() != "")
str += " and 消费者='" + cxperson.SelectedItem.ToString()+"'";
str += " and 消费日期>= #" + cxBegintime.Value.ToShortDateString() + "# and 消费日期<= #" + cxEndTime.Value.ToShortDateString() + "# ";
MessageBox.Show(str);
//执行查询
DBconn dbClass=new DBconn(sql);
OleDbCommand olecommand = new OleDbCommand(str, dbClass.Conn);
dbClass.Conn.Open();
olecommand.ExecuteNonQuery();
dbClass.Conn.Close();
//显示查询
DataSet ds = dbClass.getdb(str);
dataGridView1.DataSource = ds.Tables[0];
}
------------------------
一小段代码!