在Windows窗体C#中更新数据库 [英] Update Database in Windows Form C#

查看:85
本文介绍了在Windows窗体C#中更新数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此命令可以更新数据库并正常工作吗?

 SqlCommand cmdupdate =新的SqlCommand();
            cmdupdate.Connection = cn;
            cmdupdate.CommandType = CommandType.文本;
            cmdupdate.CommandText = "  +
                "  +
                "  +
                "  +
                "  +
                "  +
                "  +  ;"; 

解决方案

wolfsor写道:

此命令可以更新数据库并正常工作吗?


不,它会失败.您正要在终止Sql语句之前串联一个逗号.看一下代码的最后一段;

 + DATENAME(年份,OrderDate)," ; "  + DATENAME(年份,OrderDate),; 


删除最后一个逗号,它将起作用.

当您询问如何更正"该语句时,还有一些补充说明;


  • 一个SqlCommand实现IDisposable接口.您最好将其封装在using指令中.
  • SqlConnection类具有一种称为"CreateCommand"的工厂方法,可用于为该特定连接创建新命令
  • 您的连接过多,以牺牲可读性为代价.示例;

     +''+'of'+''


    用这种形式会更易读;
    '


 +'

Can this command update the database and work?

SqlCommand cmdupdate = new SqlCommand();
            cmdupdate.Connection = cn;
            cmdupdate.CommandType = CommandType.Text;
            cmdupdate.CommandText = "UPDATE Orders2 " +
                " SET Monthname= DATENAME (MONTH, OrderDate)," +
                " Weekname = DATENAME (WEEKDAY, OrderDate) +' '+ 'of' +' '+ DATENAME (MONTH, OrderDate)," +
                " Yearname = DATENAME (YEAR, OrderDate)," +
                " MonthYear = DATENAME (MONTH, OrderDate) + ' '+ DATENAME(YEAR, OrderDate)," +
                " QuarterNum = 'Quarter' + ' ' + DATENAME (QUARTER, OrderDate) +' ' + 'of' + ' ' + DATENAME (YEAR, OrderDate)," +
                " Weeknum = 'Week' + ' ' + DATENAME (WK, OrderDate) +' '+ 'of' +' '+ DATENAME (YEAR, OrderDate)," + ";";

解决方案

wolfsor wrote:

Can this command update the database and work?


Nope, it''ll fail. You''re concatenating a comma just before terminating the Sql statement. Take a look at the last piece of the code;

+ DATENAME (YEAR, OrderDate)," + ";";


That would result in this;

+ DATENAME (YEAR, OrderDate),;


Remove that last comma, and it would work.

Some additional remarks, as you asked how to ''correct'' the statement;


  • A SqlCommand implements the IDisposable interface. You''d best encapsulate it in a using directive.
  • The SqlConnection class has a factory-method called "CreateCommand" that you can use to create a new command for that particular connection
  • You''re concatenating too much, at the expense of readability. Example;

    +' ' + 'of' + ' ' 


    would be more readable in this form;

    +' of '


这篇关于在Windows窗体C#中更新数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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