How do I to insert data into an SQL table using C# as well as implement an upload function?

前端 未结 2 1109
猫巷女王i
猫巷女王i 2020-12-31 07:10

Below is the code I am working with to try to insert data into my \'ArticlesTBL\' table. I also want to upload an image file to my computer.

I am getting an error r

相关标签:
2条回答
  • 2020-12-31 07:54
    using System;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace InsertingData
    {
        class sqlinsertdata
        {
            static void Main(string[] args)
            {
                try
                { 
                SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
                conn.Open();
                    SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
                    cmd.ExecuteNonQuery();
                    Console.WriteLine("Inserting Data Successfully");
                    conn.Close();
            }
                catch(Exception e)
                {
                    Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t"  + e.GetType());
                }
                Console.ReadKey();
    
        }
        }
    }
    
    0 讨论(0)
  • 2020-12-31 08:09

    You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

    string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
    query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";
    
    SqlCommand myCommand = new SqlCommand(query, myConnection);
    myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
    myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
    // ... other parameters
    myCommand.ExecuteNonQuery();
    

    Exploits of a Mom

    (xkcd)

    0 讨论(0)
提交回复
热议问题