簡體   English   中英

從C#應用程序文本框中將值插入MySQL數據庫

[英]Inserting Values into MySQL database from C# application text box

這是我的插入方法:

public void Insert(string table, string column, string value)
{


    //Insert values into the database.

    //Example: INSERT INTO names (name, age) VALUES('John Smith', '33')
    //Code: MySQLClient.Insert("names", "name, age", "'John Smith, '33'");
    string query = "INSERT INTO " + table + " (" + column + ") VALUES (" + value + ")";


    try
    {
        if (this.Open())
        {
            //Opens a connection, if succefull; run the query and then close the connection.

            MySqlCommand cmd = new MySqlCommand(query, conn);

            cmd.ExecuteNonQuery();
            this.Close();
        }
    }
    catch { }
    return;
}

然后這是我應該實際添加用戶的按鈕點擊:

private void createUser_Click_1(object sender, EventArgs e)
{

    //Example: INSERT INTO names (name, age) VALUES('John Smith', '33')
    //Code: MySQLClient.Insert("names", "name, age", "'John Smith, '33'");

    //gets the next userid to assign to the new user
    int counter = sqlClient.Count("UserList") + 1;

    //testing just to make sure values are correct 
    User user1 = new User(counter, textEmail.Text, textPass.Text, textLNAME.Text, textFNAME.Text);
    currentUser.AppendText(user1.ToString());

    //This works to add a user manually to the table
    //This is what I want to automate
    sqlClient.Insert("UserList", "userid, email, password, lastname, firstname", "counter, textEmail.Text, textPass.Text, textLNAME.Text, textFNAME.Text");

    //just to let the user know it worked
    reaction.Text = "Success!";
}

可能有一些我從未聽說過或使用過的方法,我只是缺少了。 我得到插入方法正在尋找插入到我的數據庫表中的字符串。 我有一系列文本框供用戶輸入他們的信息,然后我想將這些字符串發送到數據庫。 如何在程序中將這些文本框值轉換為字符串? 請原諒,我對此非常陌生。

正如Jonesy所提到的,你絕對應該使用parameters來防止SQL injection

我想如果你是C#新手,那么以“好”的方式學習基礎知識並不是一個壞習慣。

您應該考慮為所有MySQL方法創建一個class ,並記住正確的object disposal

例如:

public bool NewUser(string name, int age)
{
    // First let's create the using statement:
    // The using statement will make sure your objects will be disposed after
    // usage. Even if you return a value in the block.
    // It's also syntax sugar for a "try - finally" block.

    using (MySqlConnection cn = new MySqlConnection("your connection string here"))
    {
        // Here we have to create a "try - catch" block, this makes sure your app
        // catches a MySqlException if the connection can't be opened, 
        // or if any other error occurs.

        try
        {
            // Here we already start using parameters in the query to prevent
            // SQL injection.
            string query = "INSERT INTO table (name, age) VALUES (@name, @age);";

            cn.Open();

            // Yet again, we are creating a new object that implements the IDisposable
            // interface. So we create a new using statement.

            using (MySqlCommand cmd = new MySqlCommand(query, cn))
            {
                // Now we can start using the passed values in our parameters:

                cmd.Parameters.AddWithValue("@name", name);
                cmd.Parameters.AddWithValue("@age", age);

                // Execute the query
                cmd.ExecuteNonQuery();
            }

                // All went well so we return true
                return true;
        }
        catch (MySqlException)
        {
            // Here we got an error so we return false
            return false;
        }
    }
}

現在,如果用戶想要在數據庫中添加新用戶,則可以調用此方法,並讓用戶知道是否一切順利。

private void createUser_Click_1(object sender, EventArgs e)
{
    yourClass cl = new yourClass();

    // We defined age as an integer in our method, so we first parse (convert)
    // the text value in our textbox to an integer.

    int age;
    int.TryParse(tbAge.Text, out age);
    if (cl.NewUser(tbName.Text, age) == true)
    {
        MessageBox.Show("New user succesfully added !");
    }
    else
    {
        MessageBox.Show("An error occured !");
    }
}

我希望你今天在這里學到了一些東西,祝你好運!

TextBox.Text已經是一個字符串

sqlClient.Insert("UserList", 
       "userid, email, password, lastname, firstname", 
       "counter," +textEmail.Text+ "," +textPass.Text+ "," +textLNAME.Text+ "," +textFNAME.Text+ ")";

一旦你掌握了基礎知識,你也應該關注SQL注入攻擊

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM