我正在开发一个使用数据库来存储和检索卡片的纸牌游戏。不幸的是,我无法从数据库中检索数据。
程序.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CardGame
{
class Program
{
static void Main(string[] args)
{
Card c = new Card();
Card d;
c.Name = "TestCard";
c.Pack = "Pack";
c.Value = 5;
c.Color = Colors.green;
c.Description = "Describing stuff";
//Database.CreateCardTable(); (Already created)
Database.InsertCard(c);
d = Database.RetrieveCard("TestCard");
Console.WriteLine(d.Name);
Console.ReadLine();
}
}
}
数据库.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlServerCe;
using System.Data;
using System.Data.SqlClient;
namespace CardGame
{
class Database
{
public static void CreateCardTable()
{
string sqlStr;
SqlCeConnection CardConn = new SqlCeConnection(Properties.Settings.Default.CardsConnectionString);
sqlStr = "CREATE TABLE Data " +
"(Name NVARCHAR(50), " +
"Pack NVARCHAR(50), " +
"Value INT, " +
"Color INT," +
"Description NVARCHAR(200))";
SqlCeCommand CardComm = new SqlCeCommand(sqlStr, CardConn);
try
{
CardConn.Open();
CardComm.ExecuteNonQuery();
Console.WriteLine("Tables Created Successfully!");
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("Error creating tables.");
}
finally
{
if (CardConn.State == ConnectionState.Open)
{
CardConn.Close();
}
}
}
public static void InsertCard(Card c)
{
SqlCeConnection CardConn = new SqlCeConnection(Properties.Settings.Default.CardsConnectionString);
try
{
CardConn.Open();
SqlCeCommand insertCommand = new SqlCeCommand("INSERT INTO Data VALUES(@Name, @Pack, @Value, @Color, @Description)", CardConn);
insertCommand.Parameters.Add("Name", c.Name);
insertCommand.Parameters.Add("Pack", c.Pack);
insertCommand.Parameters.Add("Value", c.Value);
insertCommand.Parameters.Add("Color", c.Color);
insertCommand.Parameters.Add("Description", c.Description);
Console.WriteLine("Card inserted successfully");
}
catch
{
Console.WriteLine("Some kind of error.");
}
finally
{
if (CardConn.State == ConnectionState.Open)
{
CardConn.Close();
}
}
}
public static Card RetrieveCard(string name)
{
Card c = new Card();
SqlCeConnection CardConn = new SqlCeConnection(Properties.Settings.Default.CardsConnectionString);
try
{
CardConn.Open();
SqlCeCommand retrieveCommand = new SqlCeCommand("SELECT * FROM Data WHERE Name=@Name", CardConn);
retrieveCommand.Parameters.Add("Name", name);
SqlCeDataReader reader = retrieveCommand.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("Reader: " + reader["Name"].ToString());
c.Name = (string)reader["Name"];
//read rest
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return c;
}
public void CreateAccountDB(string DBName)
{
}
}
}
当我运行插入卡时,我确实收到一条成功消息(在 try 语句的末尾)。当我这样做时Database.RetrieveCard("TestCard");
,它到达了行while (reader.Read())
,但我的程序没有到达 while 语句内的代码。如何修复我的代码以便我可以从数据库中读取卡片?