无法选择带有DAL的SQL查询以在消息框中显示 [英] Cannot select SQL query with DAL to show in message box

查看:57
本文介绍了无法选择带有DAL的SQL查询以在消息框中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在DAL到SQL服务器上有一个连接。使用此连接我试图阅读查询。我尝试过使用ExecuteReader()和ExecutreNonQuery()没有运气。

这是我的代码:



I have a connection in a DAL to SQL server. Using this connection I am trying to read the query. I have tried using ExecuteReader() and ExecutreNonQuery() with no luck.
Here is my code:

      private void button1_Click(object sender, EventArgs e)
        {
                    try{
            var cn = new Connection_Handler();
            string input = selectinput.Text;
            string reader = cn.Execute_SQL(input).ToString();
            MessageBox.Show(reader);
                        }
            catch(Exception ex){
                MessageBox.Show(ex.Message);
            }
}
    class Connection_Handler
    {
        SqlConnection cn;
        void ConnectiontoSQL()
        {
            string str = "server=xxx; database=jobSearch; user=sa; password=xxx";
            cn = new SqlConnection(str);
            cn.Open();            
        }
        public int Execute_SQL(string select)
        {
            ConnectiontoSQL();
            string Query = "select " + select + " from jobSearch where searchID = 1";
            SqlCommand cmd = new SqlCommand(Query, cn);
            SqlDataReader reader = cmd.ExecuteReader();
            return Convert.ToInt32(reader);
        }
    }





我的错误消息是无法将'sqldatareader'类型的对象强制转换为'' iconvertible'



my error message is "unable to cast object of type 'sqldatareader' to type 'iconvertible' "

推荐答案

您可以使用reader.GetInt32(),但应检查它是否为NULL。如果不确定数据字段的类型最好是作为字符串获取并将其解析为Int32。
You can use reader.GetInt32() but should check if it's NULL. If not sure type of data field best to get as a string and parse it as an Int32.


这篇关于无法选择带有DAL的SQL查询以在消息框中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆