连接 sql 语句是一个坏方法(安全问题),您的数据库将成为Sql 注入的简单目标。
我建议您使用存储过程来添加或修改您想要的数据,并使用 SqlParameters 从用户界面发送输入。
可能有所帮助:如何创建存储过程
这是一个代码示例,向您展示如何使用 C# 调用带参数的存储过程
//The method that call the stored procedure
public void AddComment()
{
using(var connection = new SqlConnection("ConnectionString"))
{
connection.Open();
using(var cmd = new SqlCommand("storedProcedure_Name", connection) { CommandType = CommandType.StoredProcedure })
{
cmd.Parameters.AddWithValue("@CommentFrom", commandFrom);
cmd.Parameters.AddWithValue("@CommentTo", commentTo);
//...And so on
cmd.ExecuteNonQuery();
}
}
}
关于如何创建存储过程的示例
CREATE PROCEDURE storedProcedure_Name
-- Add the parameters for the stored procedure here
@CommentFrom nvarchar(255) = NULL,
@CommentTo nvarchar(255) = NULL
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO Comments (CommentFrom, CommentTo) VALUES(@CommentFrom, @CommentTo)
END
GO