我想使用以下代码显示来自Database的数据:
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."}
请帮忙!
在字符串中间,文件路径中间有一个新行,它找不到该文件.将您的连接字符串全部放在一行,它应该解决问题.
所以:
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";