我对此字符串连接感到困惑
可以请一些正文告诉我这个字符串串联是怎么发生的?
我遇到的困惑是,+, "", '
如何在这个
int i = Magic.Allper("insert into tbl_notice values ('" + Label1.Text + "','" + companyTxt.Text + "','" + txtBranch.Text + "','" + dateTxt.Text + "' ,'" + reportingTxt.Text + "','" + venueTxt.Text + "','" + eligibilityTxt.Text + "')");
答案 0 :(得分:3)
两个"
字符之间的任何内容都被视为Java中的字符串,因此"','"
生成','
。 SQL要求包含在'
中的字符串。因此"'" + venueTxt.Text + "'"
在进行查询时会解析为'variable value'
。
答案 1 :(得分:2)
我强烈建议您不要在SQL查询中使用字符串连接。他们提出了SQL注入。这将导致安全问题。
<强> What is SQL Injection? 强>
在回答您的问题时,此连接只需要获取每个TextBox.Text
属性值并将其连接到您的insert语句中。
我强烈建议您使用ADO.NET使用参数化查询lise以下示例(假设SQL Server):
using (var connection = new SqlConnection(connString))
using (var command = connection.CreateCommand()) {
string sql = "insert into tbl_notice values(@label1, @companyTxt, @txtBranch, @dataTxt, @reportingTxt, @venueTxt, @eligibilityTxt)";
command.CommandText = sql;
command.CommandType = CommandType.Text;
SqlParameter label1 = command.CreateParameter();
label1.ParameterName = "@label1";
label1.Direction = ParameterDirection.Input;
label1.Value = Label1.Text;
SqlParameter companyTxt = command.CreateParameter();
companyTxt.ParameterName = "@companyTxt";
companyTxt.Direction = ParameterDirection.Input;
companyTxt.Value = companyTxt.Text;
// And so forth for each of the parameters enumerated in your sql statement.
if (connection.State == ConnectionState.Close)
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
答案 2 :(得分:2)
("insert into tbl_notice values ('" + Label1.Text + "','" + companyTxt.Text + "','" + txtBranch.Text + "','" + dateTxt.Text + "' ,'" + reportingTxt.Text + "','" + venueTxt.Text + "','" + eligibilityTxt.Text + "')");
假设
上述值在SQL语句中被替换,使其看起来像
("insert into tbl_notice values ('" + Hello + "','" + ABC + "','" + Engineering + "','" + 2010-12-01 + "' ,'" + Fergusson + "','" + Batcave + "','" + No + "')");
“+”运算符连接字符串值,结果为
("insert into tbl_notice values ('Hello','ABC','Engineering','2010-12-01' ,'Fergusson','Batcave','No')")
答案 3 :(得分:1)
为清晰起见,我会使用string.Format方法
int i = Magic.Allper(string.Format("insert into tbl_notice values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",
Label1.Text,
companyTxt.Text,
txtBranch.Text,
dateTxt.Text,
reportingTxt.Text,
venueTxt.Text,
eligibilityTxt.Text));
您可能还想创建一个扩展方法,以确保以这种方式将字符串安全地传递给SQL
public static string ToSqlFormat(this string mask, params string[] args)
{
List<string> safe = args.ToList();
safe.ForEach(a => a.Replace("'", "''"));
return string.Format(mask, safe);
}
可以让你写
string insert = "insert into tbl_notice values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')";
int i = Magic.Allper(insert.ToSqlFormat(
Label1.Text,
companyTxt.Text,
txtBranch.Text,
dateTxt.Text,
reportingTxt.Text,
venueTxt.Text,
eligibilityTxt.Text));