簡體   English   中英

使用C#中的Visual Studio通過MySQL將數據插入數據庫

[英]Insert Data into database via mySQL using visual studio in C#

因此,我試圖將數據插入SQL數據庫,該數據庫是通過基於服務的數據庫在Visual Studio 2017中創建的。

這是代碼

    private void save() { 
        Book book = new Book();
        book.Id = System.Convert.ToInt32(idtxtbox.Text);
        book.title = titletxtbox.Text;
        book.author = authortxtbox.Text;

        string query = "INSERT INTO Book VALUES(" + System.Convert.ToInt32(idtxtbox.Text) + "," + titletxtbox.Text + "," + authortxtbox.Text + ")";

        using (conn = new SqlConnection(connString))
        using (SqlCommand command = new SqlCommand(query, conn)) {
            conn.Open();
            command.ExecuteNonQuery();// Error here
            conn.Close();
        }
            clear();
    }

如果我輸入像

id = 001
title = "The Book"
Author = "Main Author"

我收到一個錯誤,指出“ System.Data.SqlClient.SqlException:'Book'附近的語法不正確。' ”。 我在做什么錯,該如何解決?

嘗試以這種方式進行操作,從而避免sql注入:

 SqlConnection conexion;

 private void save() {

    conexion = cConexion.getConexion(); 

    SqlCommand comand = new SqlCommand();
    comand.Connection = conexion;
    comand.CommandText = "INSERT INTO Book(Id, title, author) VALUES(@Id, @title, @author)";
    comand.Parameters.Add("Id", SqlDbType.Int, 3).Value = this.idtxtbox.Text;
    comand.Parameters.Add("title", SqlDbType.NChar).Value = this.titletxtbox.Text;
    comand.Parameters.Add("author", SqlDbType.NChar).Value = this.authortxtbox.Text;
    comand.ExecuteNonQuery();

    clear();
 }

我喜歡使用連接類來處理連接

class cConexion
{
    private static SqlConnection conexion;

    public static SqlConnection getConexion()
    {
        if (conexion != null)
        {
            return conexion;
        }
        conexion = new SqlConnection(Properties.Settings.Default.MyConnectionString);
        try
        {
            conexion.Open();
            return conexion;
        }
        catch (Exception e)
        {
            System.Windows.Forms.MessageBox.Show("Error" + e.Message);
            return null;
        }
    }

    public static void cerrarConexion()
    {
        if (conexion != null)
        {
            conexion.Close();
        }
    }
}

暫無
暫無

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

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