C# 在插入数据库之前将字符串转换为位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1695450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting String to bit before inserting into the database
提问by vix
Can anyone help in converting string value in C# to bit equivalent in Sql. I'm trying to bulkcopy the values of a datatable into Sql table. All the values I've in the datatable are in string format. When I try to bulkcopy to SQL table I'm getting an error for bit datatype columns.Can anyone please post the C# code to convert string to bit type before I bulkcopy to SQL table.
任何人都可以帮助将 C# 中的字符串值转换为 Sql 中的位等效值。我正在尝试将数据表的值批量复制到 Sql 表中。我在数据表中的所有值都是字符串格式。当我尝试批量复制到 SQL 表时,我收到位数据类型列的错误。在批量复制到 SQL 表之前,任何人都可以发布 C# 代码以将字符串转换为位类型。
Thanks, Vix
谢谢,维克斯
回答by Daniel Pryden
The bit
data type in SQL Server matches up to the bool
data type in C#. So just convert your strings to bool
s (using bool.Parse()
or your favorite alternative) and you should be set.
在bit
SQL Server中的数据类型匹配起来的bool
在C#中的数据类型。因此,只需将您的字符串转换为bool
s(使用bool.Parse()
或您最喜欢的替代方法),您就应该设置好了。
回答by Ray Burns
If your strings are "true" and "false" (ignoring case and whitespace) this will work:
如果您的字符串是“真”和“假”(忽略大小写和空格),这将起作用:
bool bit = bool.Parse(str);
If your strings are something else, you could use:
如果你的字符串是别的东西,你可以使用:
bool bit = !string.IsNullOrEmpty(str) &&
(str[0]=='Y' || str[0]=='y' || str[0]=='T' || str[0]=='t' || str[0]=='1');
SQL wants a bool value.
SQL 需要一个布尔值。
回答by gbn
SQL Server will recognise "true" and "false" for the bit datatype. Also, zero stores zero, non-zero stores as "1".
SQL Server 将识别位数据类型的“真”和“假”。此外,零存储零,非零存储为“1”。
Are you sending "true"
or true
?
你是寄"true"
还是true
?
If you get the same error with doubles (as per comments to other answers), then I suspect you are sending quotes.
如果双打出现相同的错误(根据对其他答案的评论),那么我怀疑您正在发送引号。
回答by sumitha.v.r
int a = Convert.ToInt32( row.ItemArray[5]);
bool b;
b = Convert.ToBoolean(a);
switch (a)
{
case 1:
b = true;
break;
case 0:
b = false;
break;
}