1

嘿伙计们,我正在使用 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,   
);

我知道这将是一些简单的事情......我只是看不到它。

4

1 回答 1

1

So, as we discussed in comments, it looks like the issue you have is with your connection string. You have:

SqlConnection cs = new SqlConnection("Data Source = (LocalDB)\v11.0; 
Initial Catalog = Database1; Integrated Security = true");

What you need is:

SqlConnection cs = new SqlConnection("Data Source = .\SqlInstanceName; 
Initial Catalog = Database1; Integrated Security = true");

The data source is the instance on your local machine, a hosted database or some other flavor of a Sql instance and the 'Initial Catalog' is the actual database name.

PS - I highly recommend that you look into the using keyword and wrap your command and connection objects with it so that when they fall out-of-scope, they are managed for you. It looks a bit like this when you use them:

using (SqlConnection cs = new SqlConnection())
{
   // Some code can go here.

   using (SqlCommand cmd = new SqlCommand())
   {
      // More code can go here.
   }
}

I have a more comprehensive answer about it on this post. Happy coding!

于 2013-11-15T03:28:28.183 回答