C# 在此int o=sc.executenonquery()中;是给错了吗;靠近'的语法不正确';system.data.sqlclient.sqlexception“;怎么办?

C# 在此int o=sc.executenonquery()中;是给错了吗;靠近'的语法不正确';system.data.sqlclient.sqlexception“;怎么办?,c#,sql-server,visual-studio,C#,Sql Server,Visual Studio,您缺少文本框1等末尾的.Text,并且您没有正确引用项目(您缺少很多')。更改: 致: 然后,转到并了解SQL注入攻击,并更改代码以防止这种情况发生 此处缺少一个撇号: SqlCommand sc=new SqlCommand ("insert into Patient_Details values('"+ textBox1.Text +"','"+ textBox2.Text +"','"+ textBox3.Text +"','"+ textBox4.Text +"','"+ textBox

您缺少
文本框1
等末尾的
.Text
,并且您没有正确引用项目(您缺少很多
'
)。更改:

致:


然后,转到并了解SQL注入攻击,并更改代码以防止这种情况发生

此处缺少一个撇号:

SqlCommand sc=new SqlCommand ("insert into Patient_Details values('"+ textBox1.Text +"','"+ textBox2.Text +"','"+ textBox3.Text +"','"+ textBox4.Text +"','"+ textBox5.Text +"');",con );
但是不要使用字符串连接来构建查询,而是使用参数化查询。否则,你就可以接受

还可以使用
using
语句来处置任何非托管资源/关闭连接

'"+textBox2 +"

首先使用正确的数据类型,我已经展示了
varchar
int

使用文本框的文本属性的示例

using (var con = new SqlConnection("Data Source=SAGAR\\SQLEXPRESS;Initial Catalog=ClinicDb;Integrated Security=True"))
{
    con.Open();

    using (var sc = new SqlCommand("insert into Patient_Details values(@col1,@col2,@col3,@col4);", con))
    {
        sc.Parameters.Add("@Col1", SqlDbType.VarChar).Value = textBox1.Text;
        sc.Parameters.Add("@Col2", SqlDbType.Int).Value = int.Parse(textBox2.Text);
        // ..
        int o = sc.ExecuteNonQuery();
        // ...
    }
}

我猜他们还需要访问文本框的.Text属性。还有,为什么执行不在try-catch中,而try-catch就是验证可能已经插入到db中的东西的地方?我没有投反对票,但我想原因是你提到他不应该使用这个代码,但是你向他展示了如何“修复”它。这样,他们就永远不会学习编写安全代码。它被接受的事实告诉我,这也是他使用的方式,他不会使用sql参数。-您不应该将SQL语句连接在一起-使用参数化查询来避免SQL注入我已经更正了所有这些n,现在它在int o=sc.ExecuteNonQuery()中显示错误;错误,因为sqlexpection未处理检查表和查询中的数据类型。我已经更正了所有这些n,现在它在int o=sc.ExecuteNonQuery()中显示错误;未处理sqlexpection时出错提供异常消息。是否被否决???先生,请您提供一个正确的代码或语法,以便使用windows窗体在我的数据库中添加数据???提供表结构(列的数据类型),以便我可以编写代码。创建表[dbo]。[Patient_Details]([Patient Id]INT NOT NULL,[Name]VARCHAR(255)NULL,[Age]INT NULL,[Gender]VARCHAR(50)NULL,[联系号码]INT NULL,[地址]文本NULL,约束[PK_患者_详细信息]主键群集([患者Id]ASC))//先生,在使用数据类型时是否有任何错误请告诉我??我已经更正了所有的n,现在它在int o=sc.ExecuteNonQuery()中显示错误;错误,因为sqlexpection为unhandled@SagarS:什么是
InnerException
消息?您使用了什么作为sql查询,您的C代码是什么,表中的列是什么(包括数据类型)?
'"+textBox2 +"
using (var con = new SqlConnection("Data Source=SAGAR\\SQLEXPRESS;Initial Catalog=ClinicDb;Integrated Security=True"))
{
    con.Open();

    using (var sc = new SqlCommand("insert into Patient_Details values(@col1,@col2,@col3,@col4);", con))
    {
        sc.Parameters.Add("@Col1", SqlDbType.VarChar).Value = textBox1.Text;
        sc.Parameters.Add("@Col2", SqlDbType.Int).Value = int.Parse(textBox2.Text);
        // ..
        int o = sc.ExecuteNonQuery();
        // ...
    }
}
textbox1.Text// in the query.
SqlCommand sc=new SqlCommand ("insert into Patient_Details values('"+textBox1.Text +"','"+textBox2.Text +"','"+textBox3.Text +"','"+textBox4.Text +"','"+textBox5.Text +"');",con );
and of course the missing apostrphe and use parametrized query.