试图从c# . net连接到sql server数据库时出错

本文关键字:server sql 数据库 出错 连接 net | 更新日期: 2023-09-27 18:10:11

代码

public string connectionString = ConfigurationManager.AppSettings["myconnection"];
public int get_details(string team1_name, string team2_name)
{
            SqlConnection con = new SqlConnection(connectionString);
            string sql = "insert into Table(team1_name,team2_name) values(@team1_name,@team2_name)";
            SqlCommand cmd = new SqlCommand(sql,con);
            cmd.Parameters.AddWithValue("@team1_name", team1_name);
            cmd.Parameters.AddWithValue("@team2_name", team2_name);
            try
            {
                con.Open();
                return cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
            }
}
当我运行这段代码时,错误提示为

类型为"System"的未处理异常。在dblayer.dll中发生InvalidOperationException

附加信息:ConnectionString属性尚未初始化。

有谁能帮我吗?

试图从c# . net连接到sql server数据库时出错

解决方案1:您需要使用以下语句来正确初始化connectionstring

public string connectionString =ConfigurationManager.ConnectionStrings
         [ConfigurationManager.AppSettings["myconnection"]].ConnectionString;

解决方案2:

Table是关键字,因此您需要将其括在方括号[]中。

替换:

string sql = "insert into Table(team1_name,team2_name) 
                                                values(@team1_name,@team2_name)";

:

string sql = "insert into [Table](team1_name,team2_name) 
                                                values(@team1_name,@team2_name)";

Try This:

连接字符串:

<configuration>
 <connectionStrings>
   <add name="conName" connectionString="Server=ServerName;initial catalog=DBName;User ID=sa;Password=sa123;"/> // SQL server Authentication
 </connectionStrings>
<configuration>
 public string connectionString = ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;

    public int get_details(string team1_name, string team2_name)
    {
        SqlConnection con = new SqlConnection(connectionString);
        string sql = "insert into Table(team1_name,team2_name) values(@team1_name,@team2_name)";
        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@team1_name", team1_name);
        cmd.Parameters.AddWithValue("@team2_name", team2_name);
        try
        {
            cmd.Connection = con;
            con.Open();
            return cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }
    }