那么如何从中获取数据?
在App.cs中,我创建了一个连接字符串
public string connectionString = "Server = DESKTOP-Q42NBTE; Database = FirstDataBase; Trusted_Connection = true";
public string ConnectionString
{
get => connectionString; set => connectionString = value;
}
还创建了一个包含所有数据的类 类BooksData:
public class BooksData
{
public string Title { get; set; }
public string Description { get; set; }
public string ImageFile { get; set; }
public int Price { get; set; }
public int PublisherID { get; set; }
public int AuthorID { get; set; }
public int BookID { get; set; }
}
和沟通的方法
public ObservableCollection<BooksData> GetBooks(string connectionString)
{
const string GetBooksQuery = "select * from Books";
var books = new ObservableCollection<BooksData>();
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = GetBooksQuery;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var book = new BooksData();
book.Title = reader.GetString(0);
book.Price = reader.GetInt32(1);
book.ImageFile = reader.GetString(2);
book.PublisherID = reader.GetInt32(3);
book.AuthorID = reader.GetInt32(4);
book.BookID = reader.GetInt32(5);
}
}
}
}
}
return books;
}
catch (Exception eSql)
{
Debug.WriteLine("Exception: " + eSql.Message);
}
return null;
}
但没有任何工作
这是我的数据库信息