Der*_*ick 0 .net c# sql-server dapper
我正在使用 Dapper 将我的代码连接到我的 LocalDB。我有很多其他函数可以完美地访问信息,可以读取它并将其带入我的程序,但由于某种原因,我将信息插入数据库的函数没有做任何事情。我已经确认没有抛出异常,并且在单击按钮时到达代码(如消息框所示),但没有任何数据保存到数据库中。我还检查了我的查询,当我直接查询数据库时它工作正常,只是当我出于某种原因让代码执行它时(因此是我的问题)。出了什么问题?
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Configuration;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace ProjectManager
{
class Database
{
// Connection Variables
private IDbConnection connection = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Database"].ConnectionString);
// Get Number of Projects
public int GetNumOfProjects()
{
return connection.Query<int>("select count(*) from Projects").FirstOrDefault();
}
// Load Projects
public ProjectPane LoadProjects(int i, Point start)
{
// Variables
string title;
string subject;
int progress;
// Load ProjectPane with Information
title = connection.Query<string>("select title from (select Row_Number() Over (Order by progress desc) as RowNum, *From Projects) t2 Where RowNum = " + i.ToString()).FirstOrDefault();
subject = connection.Query<string>("select subject from (select Row_Number() Over (Order by progress desc) as RowNum, *From Projects) t2 Where RowNum = " + i.ToString()).FirstOrDefault();
progress = connection.Query<int>("select progress from (select Row_Number() Over (Order by progress desc) as RowNum, *From Projects) t2 Where RowNum = " + i.ToString()).FirstOrDefault();
ProjectPane p = new ProjectPane(title, subject, progress);
p.Location = start;
p.LoadData();
return p;
}
// Create Project Entry
public void CreateProject(string title, string subject, int progress)
{
try
{
connection.Query($"insert into Projects (title, subject, progress) values ('Hello', 'There', 50)");
MessageBox.Show("Project Created");
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
// Edit Project
// Complete Projects
// Delete Project
}
Run Code Online (Sandbox Code Playgroud)
}
使用 Execute 而不是 Query
string sql = "INSERT INTO Customers (CustomerName) Values (@CustomerName);";
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
var affectedRows = connection.Execute(sql, new {CustomerName = "Mark"});
Console.WriteLine(affectedRows);
var customer = connection.Query<Customer>("Select * FROM CUSTOMERS WHERE CustomerName = 'Mark'").ToList();
FiddleHelper.WriteTable(customer);
}
Run Code Online (Sandbox Code Playgroud)