简体   繁体   中英

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

So I'm trying to insert data into an SQL Database, which was created in Visual Studio 2017 via a Service-Based Database.

Here is the code

    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();
    }

If I enter data like

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

I get an error that says " System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Book'.' ". What am I doing wrong, and how can I fix it?

Try to do it this way and thus avoid sql injections:

 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();
 }

I like to use a connection class to handle the connections

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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM