c# - 也不例外,但我的数据没有写入 SQL Server 数据库
问题描述
在将新数据条目插入 SQL Server 数据库时,我陷入了困境。我有我想存储在以下课程中的所有信息:
public class NewSearchQuery //object reference q
{
public string Name, Location, SearchType, Path, Method;
public int RefNum;
public double Fee;
public bool Paid;
}
在用户填写表格等之后。这是我将信息保存到数据库的代码:
bool complete;
string sql = $"Insert into PrivateLog (Id,Applicant,ApplicationDate,Location,Search,Paid,Method,Amount,Files) values({q.RefNum}, '{q.Name}', {AppDate}, '{q.Location}', '{q.SearchType}', {q.Paid}, '{q.Method}', {q.Fee}, '{q.Path}')";
cnn.Open();
try
{
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(sql, cnn); //The Connection String cnn is in a public string variable above this method.
adapter.InsertCommand = new SqlCommand(sql, cnn);
command.Dispose();
complete = true;
}
catch (System.Exception e)
{
complete = false;
}
cnn.Close();
return complete;
这是我的表设计器的样子:
谁能告诉我为什么新的数据输入可能无法通过?
解决方案
在这种情况下,您不需要 SqlDataAdapter,您可以简单地执行您的命令:
try
{
SqlCommand command = new SqlCommand(sql, cnn);
command.ExecuteNonQuery();
complete = true;
}
尽管我建议使用 command.Parameters 添加参数值,以保护可能的 SQL 注入:
bool complete;
string sql = "Insert into PrivateLog (Id, Applicant, ApplicationDate, Location, Search, Paid, Method, Amount, Files) values(@RefNum, @Name, @AppDate, @Location, @SearchType, @Paid, @Method, @Fee, @Path)";
cnn.Open();
try
{
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.Add("@RefNum", SqlDbType.Int).Value = q.RefNum;
command.Parameters.Add("@Name", SqlDbType.VarChar).Value = q.Name;
command.Parameters.Add("@AppDate", SqlDbType.DateTime).Value = AppDate;
command.Parameters.Add("@Location", SqlDbType.VarChar).Value = q.Location;
command.Parameters.Add("@SearchType", SqlDbType.VarChar).Value = q.SearchType;
command.Parameters.Add("@Paid", SqlDbType.Bit).Value = q.Paid;
command.Parameters.Add("@Method", SqlDbType.VarChar).Value = q.Method;
command.Parameters.Add("@Fee", SqlDbType.Decimal).Value = q.Fee;
command.Parameters.Add("@Path", SqlDbType.VarChar).Value = q.Path;
command.ExecuteNonQuery();
command.Dispose();
complete = true;
}
catch (System.Exception e)
{
complete = false;
}
cnn.Close();
return complete;
推荐阅读
- javascript - 我可以从我的 nuxt.js 项目中获得 - 我所有潜在路线的列表吗?
- java - SpringBoot应用程序远程调试异常
- c - C++中的Socket程序在服务器和客户端之间来回发送消息
- angular - 第二次调用观察者下一个似乎不起作用
- selenium - 在 Selenium 中,我如何在这个标签 Mahesh Wagh 中获取文本“Mahesh Wagh”
- spring-boot - [Jxls]为什么找不到SetFunction方法?
- java - Intellij 找不到运行 Springboot 应用程序的 Jar
- excel - Workbook_SheetChange 事件在不应触发时触发两次
- angular - Angular 6 中的手动导航
- blazor - 找不到错误解决方法 Httpclient 服务未注册