I'm using Dapper to connect my code to my LocalDB. I have plenty of other functions that perfectly access the information and can read it and bring it out into my program, but for some reason my function to insert information into the database doesn't do anything. I've confirmed that no exceptions are being thrown, and the code is reached when the button is clicked (as the messagebox shows), but none of the data saves into the DB. I also checked my query and it works fine when I directly query the DB, just not when I have the code execute it for some reason (Hence my problem). What is going wrong?
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
}
}
Use Execute instead of 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);
}