简体   繁体   English

为什么我在C#中的SQL代码不起作用?

[英]Why is my SQL code in C# not working?

I wrote a SQL command to save some items in my database. 我写了一个SQL命令来保存我的数据库中的一些项目。 But when I run it, it gives an error message: 但是当我运行它时,它会给出一条错误消息:

在此输入图像描述

And here is my code: 这是我的代码:

public void Opslaan(string titel, string rVoornaam, string rAchternaam, decimal beoordeling, string a1Voornaam, string a1Achternaam, string a2Voornaam, string a2Achternaam, string a3Voornaam, string a3Achternaam)
    {
        if (beoordelingBest < beoordeling)
        {
            titelBest = titel;
            beoordelingBest = beoordeling;
        }
        string queryString = "INSERT INTO Films (titel, beoordeling) VALUES('" + titel + "', " + beoordeling + ");" +
                             "INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a1Voornaam + "' , '" + a1Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
                             "INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a2Voornaam + "' , '" + a2Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
                             "INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a3Voornaam + "' , '" + a3Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
                             "INSERT INTO Regisseurs (voornaam, achternaam, FilmID) VALUES('" + rVoornaam + "' , '" + rAchternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));";
        command = new SqlCommand(queryString, con);

Can someone please help me with this? 有人可以帮我这个吗? I can't figure it out. 我无法弄清楚。

  1. Use parametererized queries and do not use string concatination. 使用参数化查询,不要使用字符串连接。 This is to prevent sql injection attacks but also errors with the values like forgetting to make sure strins are escaped (if a string contains a ' for example). 这是为了防止sql注入攻击,但也有错误的值,如忘记确保strins被转义(如果一个字符串包含'例如)。
  2. If you have multiple queries each unique parameter value should have its own parameter name/value 如果您有多个查询,则每个唯一参数值都应具有自己的参数名称/值
  3. Wrap your ado.net database types (SqlConnection, SqlCommand, etc) in using blocks if they are disposable 如果它们是一次性的,请using块包装您的ado.net数据库类型(SqlConnection,SqlCommand等)
  4. Never reuse connections as global objects, create, use, and destroy them when needed. 永远不要将连接重用为全局对象,在需要时创建,使用和销毁它们。

Here is the updated code with 1 statement, you can append additional statements to this and add more parameters as necessary. 这是带有1个语句的更新代码,您可以向其附加其他语句,并根据需要添加更多参数。

var query = "INSERT INTO Acteurs (voornaam, achternaam, FilmID) SELECT @a1Voornaam, @a1Achternaam, FilmID from Films WHERE titel = @title";

using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(queryString, con))
{
  command.Parameters.Add(new SqlParameter("@a1Voornaam", SqlDbType.VarChar){Value = a1Voornaam});
  command.Parameters.Add(new SqlParameter("@achternaam", SqlDbType.VarChar){Value = achternaam});
  command.Parameters.Add(new SqlParameter("@title", SqlDbType.VarChar){Value = title});

  con.Open();
  command.ExecuteNonQuery();
}

Perhaps one of your values is '); 也许你的一个价值观是');

That would terminate the INSERT statement early, and cause the error. 这将提前终止INSERT语句,并导致错误。

                                                   |
                                                   V
  INSERT INTO Films (titel, beoordeling) VALUES('');,'anything');

You should use SqlParameters instead of string concatenation. 您应该使用SqlParameters而不是字符串连接。

Are you using TextBoxes? 你在使用TextBoxes吗? I can't tell for sure. 我无法确定。 Try something like this, and change to suit your specific needs. 尝试这样的事情,并根据您的具体需求进行更改。

using System.Data.SqlClient;

protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.
ConfigurationManager.ConnectionStrings["con"].ToString());
    try
    {
        string query = "insert into UserDetail(Name,Address) 
        values('" + txtName.Text + "','" + txtAddress.Text + "');";
        SqlDataAdapter da = new SqlDataAdapter(query, con);
        con.Open();
        da.SelectCommand.ExecuteNonQuery();
        con.Close();
        lblmessage.Text = "Data saved successfully.";
    }
    catch
    {
        con.Close();
        lblmessage.Text = "Error while saving data.";
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM