0

Hello I have a simple question that regards inserting data into a MS MySql Database 2012 table. The table that I have is called COMPLETED and has 3 fields.

  • student_ID (int, NOT allowed nulls)
  • completed (bool, NOT allowed nulls)
  • random_code (string, allowed nulls)

In c# I have a list filled with unique random codes. I want all codes inserted into the database, so if I have 20 records I want 20 unique codes inserted into the random_code field. So the first records gets the first code, the seconds records gets the second code and so on. I think the best way to do this is using a foreach and, for each code in the list of codes insert that code into the random_code field in my database. The problem is I don't know how to do this. I have the following code that give's me an error at VALUE:

Incorrect syntax near 'VALUE'.

        foreach (string unRaCo in codes)
        {
            //insert database
            SqlCommand toDB = new SqlCommand("INSERT INTO COMPLETED (random_code) VALUE ( '"+ unRaCo +"' ) ", conn);
            SqlDataReader toDBR;
            toDBR = toDB.ExecuteReader();
        }

Could anyone give me a dircetion here? Thanks in advance.

EDIT:

Okay I totally changed my query as I figured out it did not yet do what I wanted it to do. I now want to update my records instead of inserting records. I did that with the following code:

        foreach (string unRaCo in codes)
        {
            //insert database
            SqlCommand naarDB = new SqlCommand("UPDATE VOLTOOID SET random_code = '"+ unRaCo +"'  ", connectie);
            SqlDataReader naarDBR;
            naarDBR = naarDB.ExecuteReader();
            naarDBR.Close();
        }

The problem this time is that the update query updates ALL records with the first code, so the first record has the code 12345 for example but all other records also have that code. I want to update 12345 into record 1 and 54321 for example in number 2, how do I do that?

4

2 回答 2

3

正确的是Valuesnot Value,即使您只提供一列。

关于您的编辑。首先要提防 SQL 注入。你最好使用 SQLParameter 类。检查配置参数和参数数据类型以获取更多信息。

如果要更新特定的 id,请使用 where 子句,如(在普通 SQL 中):

UPDATE VOLTOOID SET random_code = @NewValue WHERE random_code = @OldValue

现在,如果您只想在特定行中添加随机数,那么您将不得不使用一些更高级的 SQL 函数。同样在普通 SQL 中,您将拥有:

;WITH MyCTE AS
(
    SELECT random_code,
           ROW_NUMBER() OVER(ORDER BY random_code) AS ROWSEQ -- This will give a unique row number to each row of your table
    FROM   VOLTOOID _code
)
UPDATE MyCTE 
SET    random_code = @NewValue 
WHERE  ROWSEQ = @YourRandomRow

由于上述查询用于 SQL 脚本执行,因此您需要定义使用的变量。

于 2013-10-31T10:38:19.750 回答
1

您的语法错误,您在应该使用“值”的地方使用“值”。如果您有 SSMS,您将能够轻松找出此类错误。

通常我在 SQL Server Management Studio 查询编辑器中创建查询,然后在 C# 中使用它。大多数时候,我尽可能使用 SQL Server 存储过程。因为我认为执行文本查询比执行过程要花费一些额外的资源

于 2013-10-31T10:40:48.867 回答