Поэтому я пытаюсь вставить данные в базу данных 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:" Неверный синтаксис рядом с "Книгой". ". Что я делаю неправильно, и как я могу это исправить?
Попытайтесь сделать это таким образом и, таким образом, избегайте инъекций 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();
}
}
}