嗨那里第一次使用stackoverflow所以嗨每一个L)
我是C#表单的初学者,我认为这是一个有趣的爱好.
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = "
+textbox1.text+"'", connection);
Int32 count = (Int32)comm.ExecuteScalar();
textbox2.Text ="Found "+ count+" Members;
Run Code Online (Sandbox Code Playgroud)
好吧它只是我从谷歌xD得到的两个代码之间的混合如何错误出现在这里textbox2.Text ="找到"+计数+"成员;
这行代码有几个问题:
textbox2.Text ="Found "+ count+" Members;
Run Code Online (Sandbox Code Playgroud)
首先,有一个语法错误.你永远不会关闭第二组报价.你这样做是这样的:
textbox2.Text ="Found "+ count+" Members";
Run Code Online (Sandbox Code Playgroud)
但是,像这样的字符串连接仍然有点混乱.你有两个文字字符串,你试图将它们添加到一个整数,这不是完全直观的(可能比它需要的慢).相反,请考虑使用格式化字符串:
textbox2.Text = string.Format("Found {0} Members", count);
Run Code Online (Sandbox Code Playgroud)
这将取值count(这是一个整数),并在string.Format()函数内部识别其字符串表示形式并将其插入格式化字符串中的占位符.
更新:它处理编译时错误.现在,您将从此处获得运行时错误:
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = "
+textbox1.text+"'", connection);
Run Code Online (Sandbox Code Playgroud)
一旦您尝试执行该SQL语句,您将从数据库中收到错误,因为生成的查询有语法错误:
SELECT COUNT(*) FROM Members where sponser = some text'
Run Code Online (Sandbox Code Playgroud)
你错过了参数的开头单引号.像这样的东西:
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = '"
+textbox1.text+"'", connection);
Run Code Online (Sandbox Code Playgroud)
但是,这很重要,你还没有完成.这行代码对一个非常常见且容易被利用的漏洞(称为SQL注入)持开放态度.您将希望摆脱直接字符串连接并使用SQL查询的参数.像这样的东西:
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = @sponser");
cmd.Parameters.Add("@sponser", textbox1.text);
Int32 count = (Int32)comm.ExecuteScalar();
Run Code Online (Sandbox Code Playgroud)
知道你还可以做很多事情来改善这一点,这一切都值得学习.你可以看到的事情是:
textbox1.text在尝试在SQL查询中使用之前检查并验证用户输入().comm.ExecuteScalar()在尝试将其直接转换为a 之前检查输出Int32(如果由于某种原因返回除整数之外的任何内容,则会产生运行时错误).