我有一个小问题,从我的应用程序插入数据到我的数据库。我没有得到任何错误,而连接或试图插入到数据库,但数据只是不被插入。我使用Visual Studio 2010与c#和SqlClient
和SQL Server 2012管理工作室。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
<summary>
Summary description for Sources
</summary>
public class Sources
{
private string conString;
public int mSourceID;
public string mSourceName;
public int mActive;
public Sources()
{
conString = WebConfigurationManager.ConnectionStrings["dbconstring"].ConnectionString;
mSourceID = 0;
mSourceName = "";
mActive = 0;
}
public void insertData()
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Sources(SourceID, SourceName, Active) VALUES(@SourceID, @SourceName, @Active)", con))
{
cmd.Parameters.Add(new SqlParameter("SourceID", mSourceID));
cmd.Parameters.Add(new SqlParameter("SourceName", mSourceName));
cmd.Parameters.Add(new SqlParameter("Active", mActive));
}
}
catch (Exception Ex)
{
Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
}
}
}
}
这里是按钮点击事件:
protected void btnOk_Click(object sender, ImageClickEventArgs e)
{
Sources src = new Sources();
src.mSourceID = 1;
src.mSourceName = "aboa";
src.mActive = 0;
src.insertData();
}
我已经检查了调试器,并没有得到任何错误抛出当我点击按钮,但当我检查我的表在我的数据库,它仍然是空的。
您需要使用ExecuteNonQuery .check下面的代码来执行查询。
public void insertData()
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Sources(SourceID, SourceName, Active) VALUES(@SourceID, @SourceName, @Active)", con))
{
cmd.Parameters.Add(new SqlParameter("SourceID", mSourceID));
cmd.Parameters.Add(new SqlParameter("SourceName", mSourceName));
cmd.Parameters.Add(new SqlParameter("Active", mActive));
cmd.ExecuteNonQuery();
}
}
catch (Exception Ex)
{
Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
}
}
}
您需要执行onquery,因为您没有返回仅插入的任何数据我们还需要finally块来确保即使出现异常连接也会被关闭
public void insertData()
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Sources(SourceID, SourceName, Active) VALUES(@SourceID, @SourceName, @Active)", con))
{
cmd.Parameters.Add(new SqlParameter("SourceID", mSourceID));
cmd.Parameters.Add(new SqlParameter("SourceName", mSourceName));
cmd.Parameters.Add(new SqlParameter("Active", mActive));
cmd.ExecuteNonQuery();
}
}
catch (Exception Ex)
{
Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
}
finally
{
con.Close();
}
}
}