You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LocalDB中playerData表找不到,插入数据报错如何解决?

插入数据时提示“Invalid object name 'playerData'”的排查与解决

数据库中已存在playerData表,但执行C#代码从jogadoras.txt向该表插入数据时,抛出System.Data.SqlClient.SqlException异常,提示Invalid object name 'playerData',尝试移动表后问题仍存在。

相关代码

public Form1()
{
       InitializeComponent();
}
public static string constr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\lupul\Documents\players.mdf;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=True;";

private static void Init()
{
    SqlConnection conn = new SqlConnection(constr);
    SqlCommand cmd;
    StreamReader sr = new StreamReader(Application.StartupPath + @"\jogadoras.txt");
    string sir;
    char[] split = { '-' };
    conn.Open();
    while ((sir = sr.ReadLine()) != null)
    {
        string[] siruri = sir.Split(split);
        cmd = new SqlCommand("INSERT INTO playerData(PlayerName) VALUES (@name)", conn);
        cmd.Parameters.AddWithValue("name", siruri[0].Trim());
        cmd.ExecuteNonQuery();
    }
    MessageBox.Show("Initializarea a fost realizata țavă", "powerr softu lu mură", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

jogadoras.txt内容

Jose Andrea
Popescu Matthew
Morman Maria

排查方向与解决办法

  • 确认连接的数据库正确性
    检查连接字符串AttachDbFilename指向的C:\Users\lupul\Documents\players.mdf是否为创建playerData表的目标数据库。LocalDB可能存在多个同名数据库文件,或路径配置错误,导致连接到无目标表的数据库。可通过SSMS连接LocalDB,验证该文件对应的数据库中是否存在playerData表。

  • 指定表的架构
    默认情况下SQL Server表属于dbo架构,若表未在该架构下,需在SQL语句中明确指定,修改插入语句为:

    INSERT INTO dbo.playerData(PlayerName) VALUES (@name)
    

    同时确认表名大小写与数据库中完全一致(若数据库启用区分大小写排序规则)。

  • 修正文件读取逻辑
    代码中使用'-'作为分隔符,但文本文件内容无该字符,Split('-')后虽不影响表不存在的错误,但会导致插入数据逻辑冗余,可直接读取整行作为玩家名称:

    while ((sir = sr.ReadLine()) != null)
    {
        cmd = new SqlCommand("INSERT INTO dbo.playerData(PlayerName) VALUES (@name)", conn);
        cmd.Parameters.AddWithValue("@name", sir.Trim());
        cmd.ExecuteNonQuery();
    }
    
  • 检查数据库文件复制设置
    若项目中players.mdf的“复制到输出目录”属性设为“始终复制”,每次编译时原始数据库文件会覆盖输出目录中的文件,导致手动创建的playerData表被清除。将该属性改为“如果较新则复制”或“不复制”即可。

内容的提问来源于stack exchange,提问作者xpl0d

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 09:42:48