简体   繁体   English

使用C#中的Visual Studio通过MySQL将数据插入数据库

[英]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. 因此,我试图将数据插入SQL数据库,该数据库是通过基于服务的数据库在Visual Studio 2017中创建的。

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'.' 我收到一个错误,指出“ System.Data.SqlClient.SqlException:'Book'附近的语法不正确。' ". ”。 What am I doing wrong, and how can I fix it? 我在做什么错,该如何解决?

Try to do it this way and thus avoid sql injections: 尝试以这种方式进行操作,从而避免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();
 }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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