c# - 插入数据库C#连接字符串错误

标签 c# sql asp.net

我在尝试在数据库中设置插入命令时遇到错误,它似乎与连接字符串有关。我对这一切都非常陌生,我正在尝试获取正确的代码以便上传到我的数据库中,并假设我使用的语法可能是错误的以及错误的原因。

这是更清晰的代码:

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;

namespace ComputingProjectwh.TestPages._1._Further_Mechanics
{
    public partial class Moments_and_Energy_Test1 : System.Web.UI.Page
    {


        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Submit_Click(object sender, EventArgs e)
        {
            if (!this.IsValid)
                return;
            int score = 0;
            List<RadioButtonList> list = new List<RadioButtonList>() { RadioButtonList1, RadioButtonList2, RadioButtonList3, RadioButtonList4, RadioButtonList5, RadioButtonList6, RadioButtonList7, RadioButtonList8, RadioButtonList9, RadioButtonList10 };
            foreach (var element in list)
            {
                if (element.SelectedValue == "Correct")
                {
                    score++;
                }

            }
            Response.Write("you scored: " + score);
            Button1.Visible = false;

            if (score != 0);
            {
                SqlConnection sqlConnection1 = new SqlConnection (@"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ComputingProjectwh-20170404101246.mdf;InitialCatalog=aspnet-ComputingProjectwh-20170404101246;IntegratedSecurity=True");

                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = "INSERT AspNetUserTestScores (Id, MomentAndEnergyTestScore) VALUES (Id, score)";
                cmd.Connection = sqlConnection1;

                sqlConnection1.Open();
                cmd.ExecuteNonQuery();
                sqlConnection1.Close();


            }

        }
    }
}

enter image description here

我真的不确定问题是什么,并且似乎无法在互联网上找到答案。任何帮助将不胜感激。

最佳答案

连接到 MSSQL 时,没有 initialcatalog,您使用了错误的连接字符串。

这是正确的语法:

  Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;

或者在您的情况下,对于可信连接:

  Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;

使用您的数据:

 SqlConnection sqlConnection1 = new SqlConnection("Server=LocalDb;Database=aspnet-ComputingProjectwh-20170404101246.mdf;Trusted_Connection=True;");

关于c# - 插入数据库C#连接字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43305801/

相关文章:

asp.net - 如何防止 LinqDataSourceWhere 子句在回发时重置?

c# - 如何在每个创建的页面中自动重复 pdf 签名

c# - 设置多个 TextBlock 的 Text 属性

c# - 如何获取当前焦点窗口的选定文本?

用于显示来自多个表的数据的 SQL 查询

mysql - 选择DML还是DDL?

java - 在android中解析JSON数组子属性

c# - 通过声卡发出蜂鸣声

c# - 从 Azure 共享网站创建 Azure 媒体服务作业

sql - Postgres : Expand JSON column into rows