如何将位值从前端存储到sql server数据库?

问题描述:

我在我的表位字段,可以存储0或1如何将位值从前端存储到sql server数据库?

在我的网页上,我宣布类似

<label>Do we have your permission to send your cell a text</label> 
<div> 
    <label> 
    <input type="radio" name="ctrluuSendSMS" id="ctrluuSendSMS" value="1">Yes</label> 
</div> 
<div> 
    <label> 
    <input type="radio" name="ctrluuSendSMS" id="ctrluuSendSMS" value="0">No</label> 
</div> 

而我提出我得到了以下错误的形式:

String was not recognized as a valid Boolean 

请帮我如何声明和如何存储到数据库

+3

显示的HTML并不能帮助我们了解正在执行插入。显示该代码。 – alroc 2014-09-02 18:37:47

我相信你应该尝试的位值传递给数据库为int,不是字符串(在代码中转换,然后作为整数参数传递给StoredProc/ORM)。

(如alroc评论,可我们看到的SQL代码?)

我假设你的表看起来像

Create Table MyTable 
(
SomePK int not null identity(1,1), 
MyBitValue bit 
) 

所以你插入/更新语句将看起来像

Declare @MyParam int = 1 -- where 1(or 0) is an integer, not a string 
Declare @MyParam2 bit = 1 
Insert Into MyTable(MyBitValue)Values(@MyParam) 
Insert Into MyTable(MyBitValue)Values(@MyParam2) 

Select * From MyTable 

Set @MyParam = 0 
Set @MyParam2 = 0 
Update MyTable Set MyBitValue = @MyParam Where SomePK = 1 
Update MyTable Set MyBitValue = @MyParam2 Where SomePK = 2 

Select * from MyTable 

编辑:我已更新我的示例以显示同时使用int和位

+1

为什么在sql有一个位类型时将它作为int传递? – JonH 2014-09-02 18:52:10

+0

你可以做到这一点,这将是完全有效的。我一直使用int(将C#中的布尔转换为int)。更新答案w /位 – 2014-09-02 19:00:14

对于Input元素的值属性,使用“True”和“False”而不是“1”和“0”。

<label>Do we have your permission to send your cell a text</label> 
<div> 
    <label> 
    <input type="radio" name="ctrluuSendSMS" id="ctrluuSendSMS" value="True">Yes</label> 
</div> 
<div> 
    <label> 
    <input type="radio" name="ctrluuSendSMS" id="ctrluuSendSMS" value="False">No</label> 
</div> 

数字字符串必须被转换为布尔之前转换为数值

Convert.ToBoolean(Convert.ToByte("1")) = True 

但“真”与“假”,将直接转换。

Convert.ToBoolean("True") = True 

http://msdn.microsoft.com/en-us/library/wh2c31dd(v=vs.110).aspx