如何从Access数据库中读取是/否值作为布尔值?
帮助我以布尔格式从MS访问中检索YES/NO
数据类型。
我尝试解析它,但它总是返回false。
更新:实际上不是问题
对不起,它确实接受YES / NO作为布尔值。
OleDbconnection dbConnect = new OleDbConnection(".....*.MDB"); dbConnect.Open(); ..... ... //xyz = dbCommand.ExecuteReader() bool value = (bool)xyz[1];
下次我会研究更多,并在询问之前发现小错误..对不起的人
希望最终让这个问题得到解决:
-
Access数据库引擎用于其内部表示
Yes/True
和No/False
内容无关紧要 。 我们得到一个System.Boolean
值。 -
在Access中,
Yes/No
字段是Yes/True
或No/False
。NULL
值为No/False
。
测试数据:
测试代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.OleDb; namespace oleDbTest { class Program { static void Main(string[] args) { string myConnectionString; myConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=C:\Users\Public\Database1.accdb;"; using (var con = new OleDbConnection()) { con.ConnectionString = myConnectionString; con.Open(); using (var cmd = new OleDbCommand()) { // just to be sure, let's force one of the values to Null cmd.Connection = con; cmd.CommandText = "UPDATE YesNoTable SET YesNoField = NULL " + "WHERE Description = 'Null'"; cmd.ExecuteNonQuery(); } using (var cmd = new OleDbCommand()) { cmd.Connection = con; cmd.CommandText = "SELECT ID, YesNoField, Description FROM YesNoTable"; OleDbDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Console.WriteLine(String.Format("Row {0}:", rdr["ID"])); bool boolValue = Convert.ToBoolean(rdr["YesNoField"]); Console.WriteLine(String.Format(" Description is: {0}", rdr["Description"])); Console.WriteLine(String.Format(" Return type is: {0}", rdr["YesNoField"].GetType())); Console.WriteLine(String.Format(" raw value is: {0}", rdr["YesNoField"])); Console.WriteLine(String.Format(" boolValue is: {0}", boolValue)); Console.WriteLine(); } } con.Close(); } Console.WriteLine("Done."); } } }
结果:
Row 1: Description is: Yes Return type is: System.Boolean raw value is: True boolValue is: True Row 2: Description is: No Return type is: System.Boolean raw value is: False boolValue is: False Row 3: Description is: Null Return type is: System.Boolean raw value is: False boolValue is: False Done.
问题是.Net的布尔值定义为
0 = false 1 = true
但MS Access使用以下值作为其布尔值
0 = false -1 = true
因此,您必须手动将此整数值转换为相应的布尔值。
false = 0 true = !false
这就是你需要知道的全部。
if (Convert.ToBoolean(ds.Tables[0].Rows[i]["UseCurrInWords"].ToString())) chkBobUseCurrencyInWords.Checked = true;
ms访问可能是.mdb文件或.accdb。
观察调试器返回的值。
我猜是真的是= = 0而假是!= 0。
根据我的记忆,yes / no实际上是1或-1的数字,其中1为真。
每个Remou校正… 0 =假,-1 =真..上次我使用Access大概是2005年,所以我不完美:)