簡體   English   中英

使用C#執行SQL查詢

[英]Executing a SQL query with C#

我想向我的數據庫添加一些信息。 我搜索了一些教程,但是都沒有用。

NonQuery可以執行他需要做的事情,因為消息框返回“成功”(1)。 但是它不會更新我的數據庫。 如果我將相同的查詢直接添加到“添加新查詢”到數據庫中,則它將起作用。

有人能幫我嗎?

我目前的班級代碼:

namespace BurnThatFat
{
    class databaseconnection
    {
        //fields
        SqlConnection connection;
        string connectionstring;

        public databaseconnection()
        {
            // fields waarde toewijzen
            connectionstring = @"Data Source=(LocalDB)\MSSQLLocalDB;" +
                @"AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True";
            connection = new SqlConnection(connectionstring);
            OpenConnection();
            CloseConnection();
        }

        public List<Object> getObjectsFromDatabase()
        {
            try
            {
                OpenConnection();
                // sql query
                // Datareader
                // sqlcommand
                // return list van objecten , objecten veranderd naar jouw wens van data.
                CloseConnection();
            }
            catch (Exception)
            {
                throw;
            }
            return new List<object>();
        }

        private bool OpenConnection()
        {
            try
            {
                connection.Open();
                return true;
            }
            catch (MySqlException ex)
            {
                switch (ex.Number)
                {
                    case 0:
                        MessageBox.Show("Cannot connect to server.  Contact administrator");
                        break;
                    case 1045:
                        MessageBox.Show("Invalid username/password, please try again");
                        break;
                }
                return false;
            }
        }

        private bool CloseConnection()
        {
            try
            {
                connection.Close();
                return true;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        public void AddGebruiker()
        {
            string query = "insert into Gebruiker VALUES(3, 'Cihan', 'Kurt', 18, 'Man', 85, 75, 'Admin1', 'Test123', 'testen');";
            using (connection)
            {
                SqlCommand command = new SqlCommand(query, connection);
                OpenConnection();
                int resultaat = command.ExecuteNonQuery();
                if (resultaat == 1)
                {
                    MessageBox.Show("succes");
                }
                else
                {
                    MessageBox.Show("fail");
                }
            }
        }
    }
}

編輯:

這是我的按鈕等的代碼:

   using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

// voor sql connectie.
using System.Data.SqlClient;



namespace BurnThatFat
{
    public partial class SignUp : Form
    {

        databaseconnection db = new databaseconnection();

        public SignUp()
        {
            InitializeComponent();
            gb_login.Visible = false;
            gb_Voornaam.Visible = false;
            gb_Achternaam.Visible = false;
            gb_leeftijdgeslacht.Visible = false;
            gb_gewicht.Visible = false;
            gb_email.Visible = false;
            gb_Start.Visible = true;


        }


        private void btn_SignUp_Click(object sender, EventArgs e)
        {
            gb_Start.Visible = false;
            gb_Voornaam.Visible = true;
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            gb_Start.Visible = false;
            gb_login.Visible = true;
        }

        private void btn_loginvolgende_Click(object sender, EventArgs e)
        {
            gb_login.Visible = false;
            // hier moet nog een GB!!!!!!
        }

        private void btn_voornaamvolgende_Click(object sender, EventArgs e)
        {


            gb_Voornaam.Visible = false;
            gb_Achternaam.Visible = true;
        }

        private void btn_achternaamvolgende_Click(object sender, EventArgs e)
        {
            gb_Achternaam.Visible = false;
            gb_leeftijdgeslacht.Visible = true;
        }

        private void btn_leeftijdvolgende_Click(object sender, EventArgs e)
        {
            gb_leeftijdgeslacht.Visible = false;
            gb_gewicht.Visible = true;
        }


        // einde registratie
        // opslaan van gegevens in database
        private void btn_emailvolgende_Click(object sender, EventArgs e)
        {
            // gebruiker = new Gebruikerklasse();
           // gebruiker.Naam = Convert.ToString(tb_voornaam.Text);
           //// gebruiker.Achternaam = Convert.ToString(tb_achternaam.Text);
          //  gebruiker.Leeftijd = Convert.ToInt32(nud_leeftijd.Value);
          ///  gebruiker.Geslacht = Convert.ToString(cb_geslacht.Text);
          //  gebruiker.Huidig_gewicht = Convert.ToInt32(nud_huidiggewicht.Value);
          //  gebruiker.Streef_gewicht = Convert.ToInt32(nud_streefgewicht.Value);
          ///  gebruiker.Gebruikersnaam = Convert.ToString(tb_gebruikersnaam2.Text);
          //  gebruiker.Email = Convert.ToString(tb_email.Text);
         //   gebruiker.Wachtwoord = Convert.ToString(tb_wachtwoordsignup.Text);

            db.AddGebruiker();
            gb_email.Visible = false;
            // hier moet nog een GB!!!!!

        }

        private void btn_gewichtvolgende_Click(object sender, EventArgs e)
        {
            gb_gewicht.Visible = false;
            gb_email.Visible = true;
        }
    }
}    

插入SQL Server數據庫的最簡單方法:

string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True";

string commandText = "INSERT INTO MyTable (ID, Name, Address) VALUES (10, 'Bob', '123 Main Street');";

using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
}

只要commandText是一個有效的查詢,它應該插入一行。 最好為您的值使用參數,而不是像我在此處那樣對參數進行硬編碼-這樣可以避免SQL注入攻擊和其他潛在問題。 您可以在Google上搜索該內容(或您現在要問的問題),然后找到大量資源來幫助您。

如果您需要更多具體的幫助,請發布詳細信息,例如嘗試運行代碼時實際發生的情況-您是否會遇到異常?

在做其他事情之前,我會清理一堆東西。

首先,一起擺脫openconnection和closeconnection方法。 並且不要在您的類中保留連接的實例屬性。 使用using語句按需創建連接,因為在using語句的結尾,編譯器將在連接的IDisposable接口實現上插入對Dispose方法的調用,它將為您自動關閉連接。

因此,清理完所有不必要的代碼后,您在該類中真正應該擁有的就是Addgebrukier方法的實現,如下所示

public void AddGebruiker()
{
        string query = "insert into Gebruiker VALUES(3, 'Cihan', 'Kurt', 18, 'Man', 85, 75, 'Admin1', 'Test123', 'testen');";
        using (SqlConnection = new SqlConnection(connectionstring))
        {
            using (SqlCommand command = new SqlCommand(query, connection))
            {
                connection.Open();
                int resultaat = command.ExecuteNonQuery();
                if (resultaat == 1)
                {
                    MessageBox.Show("succes");
                }
                else
                {
                    MessageBox.Show("fail");
                }
            }
        }
    }

您還應該從app / web.config中的部分加載連接字符串,但是稍后可以在運行它之后執行此操作。

這是一個簡單的概念,應該對您來說非常合適。 只需更改ServerName,DatabaseName等。

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = null;
            SqlConnection connection ;
            SqlDataAdapter adapter = new SqlDataAdapter();
            string sql = null;
            connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
            connection = new SqlConnection(connetionString);
            sql = "insert into product (Product_id,Product_name,Product_price) values(6,'Product6',600)";
            try
            {
                connection.Open();
                adapter.InsertCommand = new SqlCommand(sql, connection);
                adapter.InsertCommand.ExecuteNonQuery();
                MessageBox.Show ("Row inserted !! ");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

暫無
暫無

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

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