如何向access表中的日期列插入日期数据 (C#实现)

最近在完善 学生宿舍管理系统 中 水电费统计模块的功能时候,涉及到了水电费数据登记日期的记录问题,运行环境是(Win2000+VS2003+Access2000),就此我专做了一个Demo,研究了此问题.

下面的代码向我们演示了如何把一个日期(date)转化成数据库所能识别接受的数据.
捕捉.jpg
  1using System;
  2using System.Drawing;
  3using System.Collections;
  4using System.ComponentModel;
  5using System.Windows.Forms;
  6using System.Data;
  7using System.Data .OleDb ;
  8using System.Globalization ;
  9
 10namespace SDMS
 11{
 12    /// 
 13    /// Form1 的摘要说明。
 14    /// 

 15    public class Form1 : System.Windows.Forms.Form
 16    {
 17        private System.Windows.Forms.Button btnOK;
 18        private System.Windows.Forms.Button btnCancel;
 19        private System.Windows.Forms.Label labID;
 20        private System.Windows.Forms.Label labDate;
 21        private System.Windows.Forms.TextBox txtID;
 22        private System.Windows.Forms.TextBox txtDate;
 23        /// 
 24        /// 必需的设计器变量。
 25        /// 

 26        private System.ComponentModel.Container components = null;
 27
 28        public Form1()
 29        {
 30            //
 31            // Windows 窗体设计器支持所必需的
 32            //
 33            InitializeComponent();
 34
 35            //
 36            // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
 37            //
 38        }

 39
 40        /// 
 41        /// 清理所有正在使用的资源。
 42        /// 

 43        protected override void Dispose( bool disposing )
 44        {
 45            if( disposing )
 46            {
 47                if (components != null
 48                {
 49                    components.Dispose();
 50                }

 51            }

 52            base.Dispose( disposing );
 53        }

 54
 55        Windows 窗体设计器生成的代码
130
131        /// 
132        /// 应用程序的主入口点。
133        /// 

134        [STAThread]
135        static void Main() 
136        {
137            Application.Run(new Form1());
138        }

139
140        private void btnOK_Click(object sender, System.EventArgs e)
141        {
142             string  str=System.Configuration .ConfigurationSettings .AppSettings ["OleDbConString"];
143             OleDbConnection con=new OleDbConnection (str);
144            try
145            {
146                
147                con.Open ();
148                string strInsert = "INSERT INTO DemoTable (ID, DateData) VALUES ( ";
149                
150                if((txtID.Text ==string.Empty )||(txtDate.Text ==string.Empty ))
151                {
152                    MessageBox.Show ("所需数据不能为空");
153                    return;
154                }

155                System.DateTime dt = DateTime.Parse(txtDate.Text,System.Globalization.CultureInfo.CreateSpecificCulture("zh-CN").DateTimeFormat);
156                
157
158                //转化返回文本框,方便显示
159                int i=int.Parse(txtID.Text);
160                string sNow = "";
161                sNow = dt.ToShortDateString();
162                txtID.Text=i.ToString();
163                txtDate.Text = '#'+sNow+'#';
164            
165                strInsert += txtID.Text+"";
166                strInsert += "CDate("+txtDate.Text+')'+")";
167                OleDbCommand cmd=new OleDbCommand (strInsert,con);
168                cmd.ExecuteNonQuery ();
169
170                MessageBox.Show ("添加成功");
171            }

172            catch(Exception err)
173            {
174                throw err;
175            }

176            finally
177            {
178
179                con.Close ();
180            }

181        }

182
183        private void btnCancel_Click(object sender, System.EventArgs e)
184        {
185            Application.Exit ();
186        }

187    }

188}

189
ps:其中txtDate也可以用DateTimePicker控件来代替,获取它的Value值既可
posted @ 2005-10-18 13:02 Kevin Li 阅读(2172) 评论(3)  编辑 收藏 所属分类: 外文翻译

  回复  引用  查看    
#1楼 2005-10-18 22:26 | 木野狐      
用参数化的方式赋值就不需要你这样拼凑 # 符号,这个做法既不安全也不可取。

strSql = "insert into yourtable(...) values(@p0, @p1, ...)";

然后向 OleDbCommand 里添加参数的时候直接赋值 DateTime 类型的时间值即可。
  回复  引用    
#2楼 2006-08-01 14:04 | chan [未注册用户]
为什么我按你说的那种方法还是不行,我的代码如下
public bool AddData(int datanum,int data,System.DateTime datetime)
{
bool tempvalue=false; //定义返回值,并设置初值
try
{
OleDbConnection conn = getConn(); //getConn():得到连接对象
conn.Open();
//设置SQL语句
string insertstr=null;
insertstr=string.Format("insert into SamplingData (datanum,data,datetime) Values('{0}','{1}','{2}')",datanum,data,datetime);

OleDbCommand insertcmd = new OleDbCommand(insertstr,conn) ;
insertcmd.ExecuteNonQuery() ;

conn.Close();
tempvalue=true;
}
catch(Exception e)
{
throw(new Exception("数据库出错:" + e.Message)) ;
}
return(tempvalue);
}
  回复  引用  查看    
#3楼 [楼主]2007-12-03 12:41 | finesite      
@chan
insertstr=string.Format("insert into SamplingData (datanum,data,datetime) Values('{0}','{1}','{2}')",datanum,data,datetime);


仔细检查上面一句,你不是按照我的方法撒!

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  博客园首页

  新闻频道

  社区

  小组

  博问

  网摘

  闪存

  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-01-17 23:20 编辑过
成果网帮您增加网站收入


相关链接: