在C#中选择时出错

本文关键字:出错 选择 | 更新日期: 2023-09-27 18:26:07

我想用以下代码显示数据库中的数据:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace TestDatabase
{
    class Program
    {
        static void Main(string[] args)
        {
            string cs = @"Data Source=(LocalDB)'v11.0;
            AttachDbFilename=C:'Users'Mani'Desktop'DOT NET'Projects'
            TestDatabase'TestDatabase'Contact.mdf;
            Integrated Security=True";
            SqlConnection con = new SqlConnection(cs);
            string query = "select * from Stu";
            SqlCommand cmd = new SqlCommand(query, con);
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                Console.WriteLine("Name: " + dr["Name"]);
            }
            con.Close();
        }
    }
}

当我运行代码时,会发生以下异常。

{"An attempt to attach an auto-named database for file C:''Users''Mani''Desktop''DOT NET''Projects'''r'n  TestDatabase''TestDatabase''Contact.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."}

请帮忙!

在C#中选择时出错

在字符串的中间,在文件路径的中间有一个新行,它找不到文件。把你的连接字符串全部放在一行上,它应该可以解决这个问题。

因此:

string cs = @"Data Source=(LocalDB)'v11.0;AttachDbFilename=C:'Users'Mani'Desktop'DOT NET'Projects'TestDatabase'TestDatabase'Contact.mdf;Integrated Security=True";

string cs = "Data Source=(LocalDB)'v11.0;"+
        "AttachDbFilename=C:'Users'Mani'Desktop'DOT NET'Projects'"+
        "TestDatabase'TestDatabase'Contact.mdf;"+
        "Integrated Security=True";