大家好,我在Visual Studios 2012中使用了连接字符串数据库设置。我试图将数据发送到数据库中,代码中没有错误,但是它没有运行,任何帮助都将是我的最佳选择现在几个小时,需要一些睡眠。谢谢。
默认页面代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace WebApplication1
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cs = new SqlConnection("Data Source = (LocalDB)\v11.0; Initial Catalog = Database1; Integrated Security = true");
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand("INSERT INTO Adopter (FIRSTNAME,LASTNAME) VALUES (@FIRSTNAME,@LASTNAME)", cs);
da.InsertCommand.Parameters.Add("@FIRSTNAME", SqlDbType.VarChar).Value = firstname.Text;
da.InsertCommand.Parameters.Add("@LASTNAME", SqlDbType.VarChar).Value = lastname.Text;
cs.Open();
da.InsertCommand.ExecuteNonQuery();
cs.Close();
}
protected void firstname_TextChanged(object sender, EventArgs e)
{
}
protected void lastname_TextChanged(object sender, EventArgs e)
{
}
}
}
SQL代码
CREATE TABLE [dbo].[Adopter] (
[FIRSTNAME] VARCHAR (50) NOT NULL,
[LASTNAME] VARCHAR (50) NOT NULL,
);
我知道这会很简单...我只是看不到它。
因此,正如我们在评论中讨论的那样,看来您的连接字符串存在问题。你有:
SqlConnection cs = new SqlConnection("Data Source = (LocalDB)\v11.0;
Initial Catalog = Database1; Integrated Security = true");
您需要的是:
SqlConnection cs = new SqlConnection("Data Source = .\SqlInstanceName;
Initial Catalog = Database1; Integrated Security = true");
数据源是本地计算机上的实例,托管数据库或Sql实例的其他某种形式,而“初始目录”是实际的数据库名称。
PS-我强烈建议您调查using关键字,并用它包装命令和连接对象,以便在超出范围时为您管理它们。使用它们时,它看起来像这样:
using (SqlConnection cs = new SqlConnection())
{
// Some code can go here.
using (SqlCommand cmd = new SqlCommand())
{
// More code can go here.
}
}
我对此有更全面的回答。祝您编码愉快!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句