[英]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.