将声明的字符串作为查询发送到使用.NET在SQL Server中编写

时间:2015-06-05 19:52:58

标签: c# mysql .net sql-server

这是我无法发送" hisname"的项目的演示代码。和#34; hisage"将变量声明为查询。实际上,每次用户输入名称和年龄时,我都需要发送一个查询,这些名称和年龄必须作为查询发送到数据库。

static void Main()
    {
        string hisname;
        int hisage;


        Console.WriteLine("Hello! Have you met a new friend?");
        string ans = Console.ReadLine();
        Console.ReadLine();
        if (ans == "y")
        {
            Console.WriteLine("Amazing! Whats his Name?");
            hisname = Console.ReadLine();                                                    
            Console.ReadLine();
            Console.WriteLine("Whats his age?");
            hisage = Convert.ToInt16(Console.ReadLine());
            Console.ReadLine();

            Console.WriteLine("Do you want me to store it?");
            Console.ReadLine();
            string ans2 = Console.ReadLine();
            if (ans2 == "y")
            {
                string SQLConnectionString = "Server=tcp:MYSERVER.database.windows.net,1433;Database=friendsadded;User ID=MYID;Password=MYPASS;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
                // Create a SqlConnection from the provided connection string.
                using (SqlConnection connection = new SqlConnection(SQLConnectionString))
                {
                    SqlCommand command = new SqlCommand();
                    command.Connection = connection;

                    command.CommandType = System.Data.CommandType.Text;
                    command.CommandText = @"INSERT INTO [myfriends] ([Friend], [Age]) VALUES ( N'hisname', 'hisage')";
                //    command.CommandText = @"SELECT TOP 10 UID, FRIEND, AGE FROM dbo.myfriends";

                    connection.Open();
                         }
                    }
             }
       }
   }
}

这里的friendsadded是数据库,而myfriends就是它下面的表。我希望它将新条目的名称和年龄添加到数据库中。

1 个答案:

答案 0 :(得分:3)

以下是使用参数的示例,而不是传递易受sql注入攻击的用户输入数据。

using (SqlConnection connection = new SqlConnection(SQLConnectionString))
{
    SqlCommand command = new SqlCommand();
    command.Connection = connection;

    command.CommandType = System.Data.CommandType.Text;
    command.CommandText = @"INSERT INTO [myfriends] ([Friend], [Age]) VALUES ( @hisname, @hisage)";
    command.Parameters.Add("@hisname", SqlDbType.VarChar, 10).Value =  hisname;
    command.Parameters.Add("@hisage", SqlDbType.Int).Value =  hisage;
    connection.Open();

    command.ExecuteNonQuery();
}