SQLException Occured

时间:2017-10-15 08:42:09

标签: asp.net

类型' System.Data.SqlClient.SqlException'的第一次机会异常。发生在System.Data.dll

我正在尝试数据库连接。但是我收到了这个错误。请帮帮我。

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 OLSWebApp
{
    public partial class ItemTypeWebForm : System.Web.UI.Page
    {
        static string constr = "server=DESKTOP-3N4UH9N; user=sa; pwd=ZEESHAN@123; Initial Catalog=Online Order System";

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {

            SqlConnection conn = new SqlConnection(constr);

            conn.Open();

            string q = "Insert INTO ItemType values ('"+ TypeIdTextBox.Text +"'), ('"+ TypeTextBox.Text +"'),('"+ NameTextBox.Text +"')";

            SqlCommand cmd = new SqlCommand(q,conn);
            cmd.ExecuteNonQuery();
        }
    }
}

con.Open()语句生成错误..

2 个答案:

答案 0 :(得分:1)

对于SQL Server连接类型,请先阅读本文档。 https://www.connectionstrings.com/sql-server/

对于您的示例,我认为DESKTOP-3N4UH9N是您的本地PC而不是服务器实例名称,不是吗?

请首先使用SQL Server Management Studio(SSMS)查找服务器实例名称。

请尝试以下代码

标准安全

using System.Data.SqlClient;

SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Server=myServerAddress; " + 
"Database=myDataBase;" + 
"User Id=myUsername;" +
"Password=myPassword;"
conn.Open();

受信任的连接

using System.Data.SqlClient;

SqlConnection conn = new SqlConnection();
conn.ConnectionString =
   "Server=myServerAddress;" +
   "Database=myDataBase;" +
   "Trusted_Connection=True;"
conn.Open();

与SQL Server实例的连接

using System.Data.SqlClient;

SqlConnection conn = new SqlConnection();
conn.ConnectionString =
  "Server=myServerName\myInstanceName;" +
  "Database=myDataBase;" +
  "User Id=myUsername;" +
  "Password=myPassword;"
conn.Open();

集成安全性

  using System.Data.SqlClient;

    SqlConnection conn = new SqlConnection();
    conn.ConnectionString =
    "Data Source=MyLocalSqlServerInstance;" +
    "Initial Catalog=MyDatabase;" +
    "Integrated Security=SSPI;"
    conn.Open();

答案 1 :(得分:0)

更改此

conn.Open();

string q = "Insert INTO ItemType values ('"+ TypeIdTextBox.Text +"'), ('"+ TypeTextBox.Text +"'),('"+ NameTextBox.Text +"')";

SqlCommand cmd = new SqlCommand(q,conn);
cmd.ExecuteNonQuery();

进入这个

conn.Open();
string q = "Insert INTO ItemType values (@id, @type ,@name)";
SqlCommand cmd = new SqlCommand(q,conn);
cmd.Parameters.AddWithValue("@id", TypeIdTextBox.Text);
cmd.Parameters.AddWithValue("@type", TypeTextBox.Text);
cmd.Parameters.AddWithValue("@name", NameTextBox.Text);
cmd.ExecuteNonQuery();
conn.Close();

确保连接可以打开而没有任何错误