0

当我尝试运行此代码时,我收到此错误:

conversion failed when converting date and/or time from character string

我在这一行得到错误:

g_muallak_tarihi = DateTime.Parse(row_muallakt["Muallak_tarihi"].ToString());

要存储既是日期又是时间或仅是日期的值,我使用 DateTime 数据类型。我不知道该怎么办。你有什么想法?

这是我的代码:

public void cs_hmuallak()
{
    string cs_hmuallak = null;
    SqlConnection cnn;

    cs_hmuallak = @"Data Source= .\SQLEXPRESS; Initial Catalog=mydb;Integrated Security= True";

    cnn = new SqlConnection(cs_hmuallak);

    try
    {
        cnn.Open();

        {
                SqlDataAdapter da_muallakt = new SqlDataAdapter("SELECT M.Muallak_tutari FROM Muallak M INNER JOIN Hasar H ON M.Hasar_no= H.Hasar_no INNER JOIN Police P ON p.Police_no=h.Police_no where p.Acenta_kodu='"+cbx_acenta.Text+"' and p.Brans_kodu='"+cbx_brans.Text+"' and  M.muallak_tarihi<=(Select M.muallak_tarihi from muallak M where M.muallak_tarihi=(select max(muallak_tarihi) from muallak where muallak_tarihi<=@parameter)) and M.Muallak_tarihi=(SELECT max(M.Muallak_tarihi) FROM Muallak M INNER JOIN Hasar H ON M.Hasar_no= H.Hasar_no INNER JOIN Police P ON p.Police_no=h.Police_no where p.Acenta_kodu='"+cbx_acenta.Text+"' and p.Brans_kodu='"+cbx_brans.Text+"' and  M.muallak_tarihi<=(Select M.muallak_tarihi from muallak M where M.muallak_tarihi=(select max(muallak_tarihi) from muallak where muallak_tarihi<=@parameter)) ) ", cnn);

                da_muallakt.SelectCommand.Parameters.AddWithValue("@parameter",g_listetarihi.ToString("yyyy-mm-dd"));
                DataTable table_muallakt = new DataTable();
                da_muallakt.Fill(table_muallakt);
                foreach (DataRow row_muallakt in table_muallakt.Rows)
                {
                    if (row_muallakt["Muallak_tutari"] != DBNull.Value)
                    {
                        if (row_muallakt["Muallak_tarihi"] != DBNull.Value)
                        {
                            g_muallak_tarihi = DateTime.Parse(row_muallakt["Muallak_tarihi"].ToString());
                            g_muallak_tutari = int.Parse(row_muallakt["Muallak_tutari"].ToString());
                        }
                    }
                }                   
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}       
4

2 回答 2

2

假设它Muallak_tarihi被定义为一DATETIME列(这应该是它所持有的),所有这些与字符串转换的工作都不需要。

您可以简单地GetDateTime直接使用数据读取器来获取它,或者简单地转换值:

g_muallak_tarihi = row_muallakt["Muallak_tarihi"] as DateTime;

此外,您使用的参数 ( @parameter)应该是DATETIME- 并且直接传入,而不是使用ToString

da_muallakt.SelectCommand.Parameters.AddWithValue("@parameter",g_listetarihi);
于 2012-08-06T09:18:24.373 回答
-1

使用字符串.格式

da_muallakt.SelectCommand.Parameters.AddWithValue("@parameter", string.Format("{0:yyyy-MM-dd}",g_listetarihi.ToString());

MSDN 日期时间格式:http: //msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

于 2012-08-06T09:14:49.193 回答