C#数据库查询错误信息?

时间:2013-08-28 06:40:03

标签: c# database ms-access error-handling

我目前正在为大学的第二个编程课工作,并且在按数据库搜索特定员工姓名时遇到问题,如果用户输入了不在数据库中的用户名,程序崩溃给出错误,而不是显示我创建的错误消息。

搜索方法:

public void searchNameDbMethod()
    {
        OleDbConnection Myconnection = null;
        OleDbDataReader dbReader = null;
        string selectionText = "";
        bool errorFlag = true;

        do
        {
            string searchName = "";
            Console.Write("Search for Employee Name: ");
            searchName = Console.ReadLine();
            searchName = searchName.ToUpper();
            Console.WriteLine("\n");

            Myconnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source= payrolldb.accdb");

            Myconnection.Open();
            selectionText = "SELECT * FROM Table1;";
            OleDbCommand cmd = Myconnection.CreateCommand();
            cmd.CommandText = selectionText;
            dbReader = cmd.ExecuteReader();

            if (dbReader.HasRows)
            {
                while (dbReader.Read())
                {
                    // since the query produces one column, the GetValue(0)           
                    //must be set                
                    // with multiple column queries, you have to know which  
                    //column holds
                    // the value that you are looking for                     
                    //field 0 = ID
                    dbName = dbReader.GetValue(1).ToString();         //1 is field 1 of the db
                    if (dbName == searchName)
                    {
                        dbName = dbReader.GetValue(1).ToString();         //1 is field 1 of the db
                        dbID = dbReader.GetValue(2).ToString();    //2 is field 2 of the db
                        dbHourlyWage = dbReader.GetValue(3).ToString();
                        dbDependents = dbReader.GetValue(4).ToString();

                        Console.Clear();
                        Console.ResetColor();
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("*******************************************************");
                        Console.WriteLine("**************** {0} *****************", date);
                        Console.WriteLine("*******************************************************");
                        Console.WriteLine("Employee Name: ", dbName);
                        Console.WriteLine("Employee ID: {0}", dbID);
                        Console.WriteLine("Hourly Wage: {0}", dbHourlyWage);
                        Console.WriteLine("Number of Dependents: {0}", dbDependents);
                        Console.WriteLine("*******************************************************");
                        Console.ResetColor();
                        Console.Write("\n\n");

                        errorFlag = false;
                    }//closes if             
                }// end of while
            }// end of if
            if (errorFlag == true)
            {
                Console.ResetColor();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Name is not in our database!");//shows the data accumulated from above       
                Console.ResetColor();
            }//closes if
            dbReader.Close();
            Myconnection.Close();
        }//close do
        while (errorFlag == true);
    }//closes searchNameDbMethod

错误: http://puu.sh/4cPWU.png

请记住,我正在为此项目使用Microsoft Access作为我的数据库(不确定是否重要)。

如何在数据库中找到名称,以便在链接的图像中显示我创建的错误消息而不是错误(崩溃程序)?

2 个答案:

答案 0 :(得分:1)

我认为您应该在SQL-Where-Clause中搜索您的员工。

selectionText = "SELECT * FROM Table1 WHERE <EmployeeName> like @Name;";

并在SQL-Query中添加一个参数。

一般我会写这样的代码:

void searchNameDbMethod()
{
    OleDbConnection Myconnection = null;
    OleDbDataReader dbReader = null;
    string selectionText = "";


    string searchName = "";
    Console.Write("Search for Employee Name: ");
    searchName = Console.ReadLine();
    searchName = searchName.ToUpper();
    Console.WriteLine("\n");

    Myconnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source= payrolldb.accdb");

    Myconnection.Open();
    selectionText = "SELECT * FROM Table1 WHERE Employee like @Name;";
    OleDbCommand cmd = Myconnection.CreateCommand();
    cmd.CommandText = selectionText;

    cmd.Parameters.Add(new OleDbParameter() { ParameterName = "@Name", Value = searchName, DbType = System.Data.DbType.String });

    try
    {
        dbReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

        while (dbReader.Read())
        {
            // since the query produces one column, the GetValue(0)           
            //must be set                
            // with multiple column queries, you have to know which  
            //column holds
            // the value that you are looking for                     
            //field 0 = ID
            string dbName = dbReader.GetValue(1).ToString();         //1 is field 1 of the db
            if (dbName == searchName)
            {
                dbName = dbReader.GetValue(1).ToString();         //1 is field 1 of the db
                string dbID = dbReader.GetValue(2).ToString();    //2 is field 2 of the db
                string dbHourlyWage = dbReader.GetValue(3).ToString();
                string dbDependents = dbReader.GetValue(4).ToString();

                Console.Clear();
                Console.ResetColor();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("*******************************************************");
                Console.WriteLine("**************** {0} *****************", date);
                Console.WriteLine("*******************************************************");
                Console.WriteLine("Employee Name: ", dbName);
                Console.WriteLine("Employee ID: {0}", dbID);
                Console.WriteLine("Hourly Wage: {0}", dbHourlyWage);
                Console.WriteLine("Number of Dependents: {0}", dbDependents);
                Console.WriteLine("*******************************************************");
                Console.ResetColor();
                Console.Write("\n\n");
            }
        }
    }
    catch
    {
        if (dbReader != null)
        {
            dbReader.Close();
        }
    }
    finally
    {
        if (Myconnection != null)
        {
            Myconnection.Close();
        }
    }
}

只是一个例子,以改善您的解决方案。

答案 1 :(得分:0)

我能够根据@BendEg

提供的一些代码来确定它

以下是我的所作所为:

public void searchNameDbMethod()
    {
        OleDbConnection Myconnection = null;
        OleDbDataReader dbReader = null;
        string selectionText = "";
        bool errorFlag = true;

        do
        {
            string searchName = "";
            Console.Write("Search for Employee Name: ");
            searchName = Console.ReadLine();
            searchName = searchName.ToUpper();
            Console.WriteLine("\n");

            Myconnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source= payrolldb.accdb");

            Myconnection.Open();
            selectionText = "SELECT * FROM Table1 WHERE employee_name='" + searchName + "'";
            OleDbCommand cmd = Myconnection.CreateCommand();
            cmd.CommandText = selectionText;
            dbReader = cmd.ExecuteReader();

            if (dbReader.HasRows)
            {
                while (dbReader.Read())
                {
                    // since the query produces one column, the GetValue(0)           
                    //must be set                
                    // with multiple column queries, you have to know which  
                    //column holds
                    // the value that you are looking for                     
                    //field 0 = ID
                    dbName = dbReader.GetValue(1).ToString();         //1 is field 1 of the db
                    if (dbName == searchName)
                    {
                        dbName = dbReader.GetValue(1).ToString();         //1 is field 1 of the db
                        dbID = dbReader.GetValue(2).ToString();    //2 is field 2 of the db
                        dbHourlyWage = dbReader.GetValue(3).ToString();
                        dbDependents = dbReader.GetValue(4).ToString();

                        Console.Clear();
                        Console.ResetColor();
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("*******************************************************");
                        Console.WriteLine("**************** {0} *****************", date);
                        Console.WriteLine("*******************************************************");
                        Console.WriteLine("Employee Name: ", dbName);
                        Console.WriteLine("Employee ID: {0}", dbID);
                        Console.WriteLine("Hourly Wage: {0}", dbHourlyWage);
                        Console.WriteLine("Number of Dependents: {0}", dbDependents);
                        Console.WriteLine("*******************************************************");
                        Console.ResetColor();
                        Console.Write("\n\n");

                        errorFlag = false;
                    }//closes if             
                }// end of while
            }// end of if
            else if (!dbReader.HasRows)
            {
                Console.ResetColor();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Name is not in our database!");//shows the data accumulated from above       
                Console.ResetColor();
            }//closes if
            dbReader.Close();
            Myconnection.Close();
        }//close do
        while (errorFlag == true);
    }//closes searchNameDbMethod

正如你所看到的,我改变了我的查询,就像他建议的那样(但没有额外复杂的东西),并将if(errorFlag == true)语句更改为else if(!dbReader.HasRows)并且它似乎像魅力!