将日期时间从C#插入到SqlServer [英] Inserting datetime from C# to SqlServer

查看:148
本文介绍了将日期时间从C#插入到SqlServer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我将日期时间从C#插入到SqlServer。但格式不兼容。



我尝试使用DateTime.Now。但是它给出了错误。



请帮忙?

Hi,

I am inserting datetime from C# to SqlServer. But format is not compatible.

I tried using DateTime.Now. But it is giving error.

Please help?

推荐答案

使用参数化查询插入它,并且它将自行排序 - 以及更安全(参见SQL注入攻击)。 Google SQLCommand.AddWithValue并使用它而不是在SQL命令字符串中包含DateTime.Now。



Insert it with a parametrised query, and it will sort itself out - as well as being safer (see SQL Injection attack). Google SQLCommand.AddWithValue and use that instead of including the DateTime.Now in your SQL command string.

会员7217874写道:
Member 7217874 wrote:

你能给出一个例子,输入多个参数插入。

Can you give an example with entering more than one parameter insertion takes place.







SqlConnection conn = new SqlConnection("your connection string");
SqlCommand cmd = new SqlCommand("INSERT INTO table_name (username, logindate) VALUES (@USERNAME, @DATE)", conn);
cmd.Parameters.AddWithValue("@USERNAME", tbUserName.Text);
cmd.Parameters.AddWithValue("@DATE", DateTime.Now);
int i = cmd.ExecuteNonQuery();


ok试试这个

................

Sql

.............

abc datetime,.......

abc是一列

,......... ............

C#

......................



ok try this
................
Sql
.............
abc datetime ,.......
abc is a columns
,......... ............
C#
......................

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string a = DateTime.Now.ToShortDateString();
                string Query = "Insert into ab values('" + a + "')";
                string con = "Data source =abc; initial catalog=ex;            integrated security= true";
                SqlConnection cn = new SqlConnection(con);
                cn.Open();
                SqlCommand cmd = new SqlCommand( Query ,cn);
                cmd.ExecuteNonQuery();
               
            }
            catch (Exception g)
            {
                label1.Text = g.Message;
            }
        }


这篇关于将日期时间从C#插入到SqlServer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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