asp.net 将位值写入数据库

ruoxqz4g  于 6个月前  发布在  .NET
关注(0)|答案(8)|浏览(85)

我试图在一个名为“processed”的字段中写入一个bit值(true或false)到我的数据库中。我目前正在尝试通过传入bool值来实现这一点,但我得到一个错误,说不能从类型varchar转换为bit。有人能看到我的逻辑中发生了什么吗?

protected void CheckBoxProcess_CheckedChanged(object sender, EventArgs e)
    {
        bool update;
        bool trueBool = true;
        bool falseBool = false;
        string checkedString = "UPDATE SecureOrders SET processed = '%" + trueBool + "%' WHERE fName LIKE '%" + DefaultGrid.SelectedRow.Cells[2].Text + "%' AND lName LIKE '% " + DefaultGrid.SelectedRow.Cells[3].Text + "%'";
        string uncheckedString = "UPDATE SecureOrders SET processed = '%" + falseBool + "%' WHERE fName LIKE '%" + DefaultGrid.SelectedRow.Cells[2].Text + "%' AND lName LIKE '% " + DefaultGrid.SelectedRow.Cells[3].Text + "%'";
        CheckBox cb = (CheckBox)sender;
        GridViewRow gvr = (GridViewRow)cb.Parent.Parent;
        DefaultGrid.SelectedIndex = gvr.RowIndex;
        update = Convert.ToBoolean(DefaultGrid.SelectedValue);

        orderByString = orderByList.SelectedItem.Value;
        fieldString = searchTextBox.Text;

        System.Configuration.ConnectionStringSettings connectionString;

        connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["secureodb"];


        // Create an SqlConnection to the database.
        using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
        {
            connection.Open();
            SqlCommand checkedCmd = new SqlCommand(checkedString, connection);
            SqlCommand uncheckedCmd = new SqlCommand(uncheckedString, connection);
            dataAdapter = new SqlDataAdapter("SELECT * FROM SecureOrders", connection);

            // create the DataSet
            dataSet = new DataSet();
            // fill the DataSet using our DataAdapter               
            dataAdapter.Fill(dataSet, "SecureOrders");

            DataView source = new DataView(dataSet.Tables[0]);
            DefaultGrid.DataSource = source;

            if (cb.Checked == true)
            {
                checkedCmd.ExecuteNonQuery();

            }
            else
            {
                uncheckedCmd.ExecuteNonQuery();
            }

            connection.Close();
        }




    }

字符串

kse8i1jr

kse8i1jr1#

您需要将位字段设置为10,具体取决于它是真还是假。
于是:

string checkedString = "UPDATE SecureOrders SET processed = 1 WHERE fName LIKE '%" + DefaultGrid.SelectedRow.Cells[2].Text + "%' AND lName LIKE '% " + DefaultGrid.SelectedRow.Cells[3].Text + "%'";
string uncheckedString = "UPDATE SecureOrders SET processed = 0 WHERE fName LIKE '%" + DefaultGrid.SelectedRow.Cells[2].Text + "%' AND lName LIKE '% " + DefaultGrid.SelectedRow.Cells[3].Text + "%'";

字符串
此外,正如在评论中提到的,直接从用户输入构造SQL语句是成为SQL注入攻击受害者的最简单方法。在这些情况下,最好使用参数化查询(甚至是存储过程)。

....
string checkedString = "UPDATE SecureOrders SET processed = 1 WHERE fName LIKE @p1 AND lName LIKE @p2";
string uncheckedString = "UPDATE SecureOrders SET processed = 0 WHERE fName LIKE @p1 AND lName LIKE @p2";


然后,您可以创建传递给ExecuteNonQuery调用的参数

SqlParameter p1 = new SqlParameter("@p1",SqlDbType.Varchar) { Value = string.Format("%{0}%",DefaultGrid.SelectedRow.Cells[2].Text) };
SqlParameter p2 = new SqlParameter("@p2",SqlDbType.Varchar) { Value = string.Format("%{0}%",DefaultGrid.SelectedRow.Cells[3].Text) };
if (cb.Checked == true)
{
    checkedCmd.Parameters.Add(p1);
    checkedCmd.Parameters.Add(p2);
    checkedCmd.ExecuteNonQuery();

}
else
{
    uncheckedCmd.Parameters.Add(p1);
    uncheckedCmd.Parameters.Add(p2);
    uncheckedCmd.ExecuteNonQuery();
}

okxuctiv

okxuctiv2#

如果你在SQL语句中注入字符串“1”表示True,“0”表示False,你就可以解决这个问题,解决这个问题的“正确”方法是参数化你的SQL语句,并将参数添加到命令对象中。然后由框架完成从VB BooleanSqlDbType.Bit的类型转换。
试试看:

string sqlString = "UPDATE SecureOrders SET processed = @Processed WHERE fName LIKE '%' + @FirstName + '%' AND lName LIKE '%' + @LastName + '%'";

字符串
还有:

SqlCommand objCmd = new SqlCommand(sqlString, connection);
        objCmd.Parameters.AddWithValue("Processed", cb.Checked);
        objCmd.Parameters.AddWithValue("FirstName", DefaultGrid.SelectedRow.Cells[2].Text);
        objCmd.Parameters.AddWithValue("LastName", DefaultGrid.SelectedRow.Cells[3].Text);


最后:

objCmd.ExecuteNonQuery();


如果你打算编写数据驱动的Web应用程序,那么了解如何避免SQL注入安全漏洞是非常重要的。有关更多信息,请访问:MSDN How To: Protect From SQL Injection in ASP.NET

qoefvg9y

qoefvg9y3#

在SQL中,位值是1或0,而不是“true”或“false”。在更新中将“true”和“false”更改为1和0,应该没问题。(注意0和1也没有引号。)

gk7wooem

gk7wooem4#

你的SQL语法是错误的-你传递了一个字符串作为值来设置processed列的值,这是你不能做的。

r9f1avp5

r9f1avp55#

最简单的方法是将布尔值Convert.ToInt16转换为true/false,0或1。

jm81lzqq

jm81lzqq6#

布尔值被连接为“true”|“false”。尝试使用三元运算符来显示“1”或“0”:

string checkedString = "UPDATE SecureOrders SET processed = '%" + (trueBool ? "1" : "0") + "%' WHERE fName LIKE '%" + DefaultGrid.SelectedRow.Cells[2].Text + "%' AND lName LIKE '% " + DefaultGrid.SelectedRow.Cells[3].Text + "%'";

字符串

new9mtju

new9mtju7#

您的SQL语句并没有试图设置任何类型的布尔值,而是试图设置文本%True%%False%
由于您将数据库字段描述为“bit”而不是“boolean”,因此在构造字符串时可能需要使用类似"processed = " + (trueBool ? 1 : 0) + "的东西。但根据您使用的SQL服务器,您可能可以使用类似processed = " + trueBool + "processed = '" + trueBool + "'的东西。
或者,在这种特殊情况下,您可以跳过插值trueBool,而只是使用一个完全常数的字符串,就像大多数其他答案所建议的那样。
另外,顺便说一句,请注意,通过在SQL语句中插入未经检查的用户输入,您将为错误和SQL注入敞开大门。例如,如果有人输入“O'Brian”作为姓氏,您将获得错误,并且使用更多恶意的值选择,他们可能能够更改数据库中的任何内容。

chy5wohz

chy5wohz8#

很老的问题,但我希望这可以帮助别人。
要从C#代码隐藏中向SQL数据库写入位值,请遵循以下示例。
1.-首先声明一个变量以获取值0或1(在本例中,它取决于Checkbox1的状态):

int isenable = 0;
            if (CheckBox1.Checked == true)
            {
                enable = 1;
            }

字符串
2.-然后创建你的连接,你的SQL查询并执行它:

string connetionString1 = null;
            SqlConnection connection1;
            connetionString1 = "Data Source=SERVERNAME;Initial Catalog=Scrapper;Persist Security Info=True;User ID=myUser;Password=Mypassword123";
            connection1 = new SqlConnection(connetionString1);
            connection1.Open();
            SqlCommand command1 = new SqlCommand(
                "INSERT INTO usuarios(numgaffete, windowsid, name, enable, email) VALUES ('" + txtgafete.Text + "', '" + txtwindowsid.Text + "', '" + txtname.Text + "', '" + Convert.ToInt16(isenable) + "', '" + Email.Text + "')",
                connection1);
            command1.ExecuteNonQuery();


请注意,在SQL Server命令中,必须将int变量(isenable)转换为int 16,以避免在执行命令时出错。

相关问题