2

我是asp.net / c#的相对论新手。我写了几个应用程序,所以我可以解释语言,但我不流利。

基本上每年我们都有学生进入大学,我希望能够有一个文本框,我可以将 SQL 代码放入其中,它会自动更新数据库。当然,此页面将受到保护。

但是像这样的东西。

(,'11JB0666@gmail.org', '12', 'Joe', 'Bloggs', 'Joseph Bloggs', '11JB0666') 

所以这将是sql脚本中VALUES的代码。

这可能吗?

我确实认为我可以使用这样的东西......

SqlConnection conn = new
 SqlConnection(ConfigurationManager.ConnectionStrings["ExtensionActivitesConnectionString"].ConnectionString);
    SqlCommand cmd = new SqlCommand(" Insert into dbo.Names (Email,Year,FirstName,LastName,Name,Username) VALUES (@SQL)", conn);
    cmd.Parameters.AddWithValue("@SQL", SqlTextBox.Text);

    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();

任何帮助或建议将非常感谢。

4

3 回答 3

8

这是一种可怕且具有潜在危险的方法。我建议您创建一个表单来收集您需要的信息,其中包含单独的、正确标记的字段。

由于您只收集少量数据,因此表单应该非常简单。在将数据插入数据库之前,它应该包括客户端和服务器端验证。

于 2012-06-06T15:53:20.470 回答
2

That won't work with a parameterized query like you're doing -- the single quotes will be escaped and the SQL sent to the server will not be valid. That pattern is used to avoid SQL injection attacks.

You would be better off creating a complete form with all the fields you want and passing the individual fields to your SQL statement. Create a separate TextBox for each field you want to insert into your Names table. In my example below, I have named them emailTextBox, yearTextBox, firstnameTextBox, lastnameTextBox, nameTextBox, and usernameTextBox.

Also, although I am providing a very basic example, you should probably validate each field before you actually send the data to the database. You should validate to ensure required fields have values as well as for format -- email for example has a very specific format, and year should probably be a number. For more information on validation, see the following:

http://msdn.microsoft.com/en-us/library/7kh55542.aspx

Example:

var qry = "Insert into dbo.Names (Email,Year,FirstName,LastName,Name,Username) " + 
          "VALUES (@email, @year, @firstname, @lastname, @name, @username)";    
var cmd = new SqlCommand(qry);
cmd.Parameters.AddWithValue("@email", emailTextBox.Text);
cmd.Parameters.AddWithValue("@year", yearTextBox.Text);
cmd.Parameters.AddWithValue("@firstname", firstnameTextBox.Text);
cmd.Parameters.AddWithValue("@lastname", lastnameTextBox.Text);
cmd.Parameters.AddWithValue("@name", nameTextBox.Text);
cmd.Parameters.AddWithValue("@username", usernameTextBox.Text);
于 2012-06-06T15:58:23.453 回答
1

从您的代码中可以清楚地看出,这些值几乎已定义并且没有任何动态,因此您应该提供适当的表格来输入数据。

这种方法很危险,并且容易发生 SQL 注入。

于 2012-06-06T15:55:17.783 回答