积极答复者
向数据库中添加记录

问题
-
您好,我在用.net 2008编写简单的winform,
其中有一个功能就是需要向ACCESS文件中写入记录.
我通过databasedataset来连接数据库文件,通过用TableAdapter.insert方法写入记录.
(本人半路出家,很多术语不会......汗,希望您能明白我的意思......)
其中有一个字段是时间类型.程序将DateTimePicker的text写入该字段中.正常写入记录没问题.
但问题在于有时我对于这个字段不需要记录,甚至不希望写成"0:00:00",而无论我用时间变量置为"nothing",还是直接输入"",在数据库中都记录为"0:00:00".
除非我将insert的对应参数直接写为nothing,数据库中的记录才为空.
该时间字段为"非必须",因此我也曾想过先建一个记录,然后通过update方法来更新记录,但是语句就显得比较多了.
有没有什么好方法可以通过insert简单的完成上述步骤?
答案
全部回复
-
您好,感谢您对我问题的关注!
我明白您的意思,而且用"nothing"也可以实现.
但比如:
Dim tempRecord As New databaseDataSetTableAdapters.库存TableAdapter
tempRecord.Insert(textbox1.text, textbox2.text, textbox3.text, DateTimerPicker1.text, DateTimerPicker2.text, DateTimerPicker3.text)
其中最后三个字段为时间类型.
如果仅有一个时间字段可能为空时可以按您的方法(比如DateTimerPicker1.text为空),用if语句来判断选择,用DBNull.value来代替,成为
tempRecord.Insert(textbox1.text, textbox2.text, text3.text, DBNull.value, DateTimerPicker2.text, DateTimerPicker3.text)
但当最后三个字段在实际录入时都有可能为空时,总不能写出2^3=8条判断语句吧?(我实际使用的时间类型的字段还有很多)
我试过,用局部变量来代替,但是局部变量无论是字符串型,还是时间类型,操作结果都是在数据库中显示为"0:00:00",而不是真正的空白.
望指教.
-
您好,感谢您对我问题的关注!
我明白您的意思,而且用"nothing"也可以实现.
但比如:
Dim tempRecord As New databaseDataSetTableAdapters.库存TableAdapter
tempRecord.Insert(textbox1.text, textbox2.text, textbox3.text, DateTimerPicker1.text, DateTimerPicker2.text, DateTimerPicker3.text)
其中最后三个字段为时间类型.
如果仅有一个时间字段可能为空时可以按您的方法(比如DateTimerPicker1.text为空),用if语句来判断选择,用DBNull.value来代替,成为
tempRecord.Insert(textbox1.text, textbox2.text, text3.text, DBNull.value, DateTimerPicker2.text, DateTimerPicker3.text)
但当最后三个字段在实际录入时都有可能为空时,总不能写出2^3=8条判断语句吧?(我实际使用的时间类型的字段还有很多)
我试过,用局部变量来代替,但是局部变量无论是字符串型,还是时间类型,操作结果都是在数据库中显示为"0:00:00",而不是真正的空白.
望指教.
-
写个函数返回要插入的值,函数里面用if判断。
The following is signature, not part of post
Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
Visual C++ MVP -
你好,
由于你在你的Access数据中这个一列设置了列的类型为 时间 类型,所以插入一个空值的时候,他会有默认的时间值出现。因为 空字符串 不是一个有效的时间值,所有Access数据库是不可能把一个时间类型的列赋上空字符串的,希望你能够理解。
关于这个问题,我们可以尝试的区使用一个字符串类型 (Text类型) 在这个列上。然后在插入和读取的时候对于不是空字符串的值做此到日期类型的转换即可!
Sincerely,
Bob Bao
Bob Bao [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
-
-
你好,
你是否在Access里面把对应的列设置了 默认值:Default Value? 如果没有设置这个值,默认Insert的时候不Insert这个列就不会在这个cell上插入值。 所以我们可以判断的来生成Insert语句。
Bob Bao [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.