sqlexception在c#中未处理

时间:2014-05-24 18:54:54

标签: c#

我不知道为什么但是当我想插入图像并保存时,SQLException会出现错误(?)

namespace Project
{
    class Connection
    {
        private SqlConnection con;
        private string connectString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Application.StartupPath + @"\Database1.mdf;Integrated Security=True;User Instance=True"; 

        private DataTable dTable;
        private SqlDataAdapter adapt; 
        private SqlDataReader read; 
        private SqlCommand cmd;

        public Connection()
        {
            con = new SqlConnection(connectString);
        }

        public DataTable executeQuery(string query)
        {
            try
            {
                if (con.State != ConnectionState.Closed)
                {
                    con.Close();
                }
            }
            catch(Exception e)
            {
                MessageBox.Show("Error in database: "+e);
            }

            con.Open();

            dTable = new DataTable();
            adapt = new SqlDataAdapter(query, connectString);
            adapt.Fill(dTable);

            return dTable;
        }

        public void executeUpdate(string query)
        {
            try
            {
                if (con.State != ConnectionState.Closed)
                {
                    con.Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Error in database: " + e);
            }

            con.Open();
            cmd = con.CreateCommand();
            cmd.CommandText = query;
            read = cmd.ExecuteReader(); // this is the error
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要在插入或更新记录时致电cmd.ExecuteNonQuery(),以便选择使用的数据cmd.ExecuteReader()

所以改变这一行:

read = cmd.ExecuteReader(); 

到此:

int NoOfRowsInserted = cmd.ExecuteNonQuery();

详情请见MSDN

此外,您可以看到此tutorial