用C#更新SQLSERVER。

C# SqlBulkCopy sqlserver 批量更新数据 在开发中遇到了一张数据因为只做了同步插入而没有做同步更新的操作,导致了百万数据不准确。面对大量数据需要更新,传统的循环逐条插入以及拼接1000条数据插入都比较耗时,网上有博主做出了相关测试。     根据以上场景,新建控制台程序。config添加数据库连接配置,sqlHelper连接更新数据源,sqlBulkCopyHelper连接更新目标库。 1,注意三点:第一点是: String sqlstring = @""; 即String sqlstring = @"SELECT [order... 阅读详情

需求:SQLSERVER中有一张表需要被更新。

方法有三:

一,直接在SQL中操作。

二,在C#中编写函数,之后deploy到SQL中,SQL中再去调用这个函数。

三,直接在C#中对着数据库操作。


这三种方法由快到慢,能用一,不用二;能用二,不用三。

有个项目要用到web service,第二种方法deploy老是出错,也不知道为什么,于是只好用第三种。

以下例子从简,不包括webservice部分,涵盖要点:

1. 多线程操作(定义线程组,设置线程完毕触发事件,等待所有线程完毕)

2. dataset update回DB(为表设置主键)

3. 用计数器设置timeout(加Timer)

4. connection string 来自 configuration


以下分别为:

主程序 Program

线程程序threadtranslate

更新回程序updateback

配置文件config


先在BD中建10张临时表,把要更新的数据按模10插入这10张表中。

然后开10个线程分别对这10张表进行操作:先抓入dataset,再对row做update。

最后将10张表依次更新回原表。

另设计时器,防止超时,时间到了直接终止程序。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Configuration;
using System.Timers;

namespace updatetest
{
    class Program
    {

        static public string strConn = ConfigurationManager.ConnectionStrings["constring"].ToString();
        static public SqlConnection con = new SqlConnection(strConn);
        static TimeSpan waitTime = new TimeSpan(0, 1, 0);

        static public AutoResetEvent[] events = new AutoResetEvent[4];

        static void Main(string[] args)
        {
            for (int j = 0; j < 4; j++)
            {
                events[j] = new AutoResetEvent(false);
            }

            con.Open();
            DateTime dtstart = System.DateTime.Now;

            QueryandUpdate();

            updateback.updateback.updatefunction();

            DateTime dtend = System.DateTime.Now;
            Console.WriteLine("all spend: {0}", dtend - dtstart);
            Console.Read();

        }


        public static void QueryandUpdate()
        {


            string sqlsplit = "";
            for (int j = 0; j < 4; j++)
            {
                sqlsplit += " if exists (select * from dbo.sysobjects where id = object_id('translationtable" + j.ToString() + "')) drop table translationtable" + j.ToString()
                + " select top 100000 TimeKey,ltrim(rtrim(DayNumberOfWeek)) AS DayNumberOfWeek into translationtable" + j.ToString() + " from testupdate where TimeKey%4=" + j.ToString()
                + " ALTER TABLE translationtable" + j.ToString() + " ADD CONSTRAINT [PK_translationtable" + j.ToString() + "_IK] PRIMARY KEY CLUSTERED ([TimeKey] ASC)";
            }

            //string sqlsplit = "exec usp_splitsurvey";

            SqlCommand commandsplit = new SqlCommand(sqlsplit, con);


            int num;
            num = commandsplit.ExecuteNonQuery();


            con.Close();

            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 60000;
            timer.Elapsed += new ElapsedEventHandler(OnTime);
            timer.Enabled = true;
            timer.Start();



            Thread[] thread = new Thread[4];

            for (int j = 0; j < 4; j++)
            {
                thread[j] = new Thread(run);
                thread[j].Start(j);
            }

            WaitHandle.WaitAll(events);


        }


        public static void run(object i)
        {
            threadtranslate.threadtranslate.th((int)i);
            events[(int)i].Set();
        }

        public static void OnTime(Object source, ElapsedEventArgs e)
        {
            Console.WriteLine("Timeout");
            Console.Read();
            System.Diagnostics.Process.GetCurrentProcess().Kill(); 
        }


    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace threadtranslate
{
    public class threadtranslate
    {
        static public void th(int i)
        {
            string constr = ConfigurationManager.ConnectionStrings["constring"].ToString();
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            DateTime dtstart = System.DateTime.Now;

            DataSet ds = new DataSet();
            SqlDataAdapter da;

            string sql = "select * from translationtable" + i.ToString();
            da = new SqlDataAdapter(sql, conn);
            SqlCommandBuilder cb1 = new SqlCommandBuilder(da);
            da.Fill(ds, "translationtable");



            for (int retrycount = 0; retrycount < 3; retrycount++)
            {
                foreach (DataRow therow1 in ds.Tables["translationtable"].Select("DayNumberOfWeek<9"))
                {
                    string ch = therow1["DayNumberOfWeek"].ToString();
                    therow1["DayNumberOfWeek"] = "1" + ch;
                }
            }

            da.Update(ds, "translationtable");
            conn.Close();

            DateTime dtend = System.DateTime.Now;

            Console.WriteLine("thread" + i.ToString() + " spend: {0}", dtend - dtstart);
            //Console.Read();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace updateback
{
    public class updateback
    {
        static public void updatefunction()
        {
            string constr = ConfigurationManager.ConnectionStrings["constring"].ToString();
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();

            string sql = "";
            for (int j = 0; j < 4; j++)
            {
                sql += " update f set f.DayNumberOfWeek = translationtable" + j.ToString() + ".DayNumberOfWeek from testupdate f inner join translationtable" + j.ToString() + " on f.TimeKey=translationtable" + j.ToString() + ".TimeKey "
                + " drop table translationtable" + j.ToString();
            }

            SqlCommand command = new SqlCommand(sql, conn);
            int num;
            num = command.ExecuteNonQuery();
            conn.Close();
        }
    }
}

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<system.serviceModel>
		<bindings>
			<basicHttpBinding>
				<binding name="BasicHttpBinding_LanguageService" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
					<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
					<security mode="None">
						<transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
						<message clientCredentialType="UserName" algorithmSuite="Default" />
					</security>
				</binding>
			</basicHttpBinding>
		</bindings>
		<client>
			<endpoint address="http://api.microsofttranslator.com/V2/soap.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_LanguageService"
                contract="BingLanguageService.LanguageService" name="BasicHttpBinding_LanguageService" />
		</client>
	</system.serviceModel>
	<connectionStrings>
		<add name="constring" connectionString= "Data Source=SIEGE;Initial Catalog=Payne;Integrated Security=True" providerName="System.Data.SqlClient"/>
	</connectionStrings>
</configuration>


YOLOv8 更换损失函数DIoU、EIoU、GIoU...Inner-IoU... 介绍了一些损失函数,并将其应用到yolov8训练中 阅读详情

相关推荐

基于 YOLOv26 的电路焊点虚焊检测系统:AI 质检实战

本文介绍了一种基于YOLOv26的电路焊点虚焊检测系统,利用深度学习技术实现自动化质检。系统能识别虚焊、桥接、少锡等8种常见焊点缺陷,具有高精度、实时性和强鲁棒性等特点。文章详细阐述了系统架构,包括数据采集、预处理、YOLOv26检测模型和后处理模块,并提供了代码实现的关键部分,如数据预处理增强和模型训练配置。该系统可显著提高电子制造业的质检效率和准确性。

一键难忘的博客 660

C#更新sqlserver数据库方法

1. DataAdapter+SqlCommandBuilder(效率低,适用于少量数据) /// <summary> /// 更新数据 /// </summary> public void UpdateData() { for (int i = 0; i < ...

qq_42678477的博客 2478

SQL Server批量插入批量更新工具类

SQL Server批量插入批量更新工具类,SqlBulkCopy,BatchUpdate

C#SQL Server数据库基本操作(增、删、改、查)

C#中连接数据库,我们需要使用System.Data.SqlClient命名空间中的SqlConnection、SqlCommand和SqlDataReader等类。连接数据库时,需要指定数据库连接字符串,并确保在使用SqlCommand时,提供正确的SQL语句和连接对象。使用这些类,我们可以轻松地执行常见的增删改查操作,以及许多其他操作。掌握数据库连接的方法可以使我们能够更轻松地开发出优秀的C#应用程序。

naer_chongya的博客 1万+

DBHelper

 using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Data.SqlClient;using System.Configuration;namespace BookDAL{    public static class DBHelper    {       

xiongyongchen的专栏 394

C# 通过DataGridview的直接更新MSSQL

C# DataGridView 更新 SQL Server数据

x15037308498的博客 1593

C# 语言 SQL Server 批量更新

本文详细介绍了C#操作SQL Server实现批量更新的多种方案。针对小数据量(1000条以内)推荐参数化SQL拼接或CASE WHEN优化;对于大数据量(1000条以上)建议使用SqlBulkCopy+临时方案或Dapper框架。重点强调了SQL注入防护、事务保护、连接释放等关键注意事项,并提供了完整的代码实现。不同场景下的最优选择:小数据量注重简洁高效,大数据量追求高性能低损耗,同时兼顾开发效率与数据安全。

StevenChen的博客 935

C#更新SQLServer中的TimeStamp字段(时间戳) 防止同时修改一行时覆盖更新

C#更新SQLServer中的TimeStamp字段(时间戳) 分类:C#2012-10-24 15:101878人阅读评论(0)收藏举报 public partial class Form1 : Form { private SqlConnection mCnn = null; private long TimeStampVa...

weixin_30369087的博客 277

如何在 Visual C# .NET 中使用 SqlDataAdapter 对象更新 SQL Server 数据

本文包含 Microsoft Visual C# .NET 代码示例,这些示例演示如何通过“SqlDataAdapter”对象,用运行在“DataSet”对象上的数据修改来 更新 SQL Server 数据库,其中“DataSet”对象使用该数据库中某个数据进行填充。

ddkxddkx的专栏 1527

C# SQLServer数据库操作:增加、删除、更新、读取

【代码】C# SQLServer数据库操作:增加、删除、更新、读取。

ForKnowledgeMe的博客 621

C#通过SqlConnection连接查询更新等操作Sqlserver数据

Sqlserver数据库连接方式有多种,这里只介绍最常用的通过SqlConnection和Sqlserver数据库用户名和密码验证来进行操作数据库。 数据库连接字符串: string connString = "data source=119.180.261.117,1433;initial catalog=anxiuyun;user id=sa;pwd=sa"; 这里data sour

凡梦 4407

sqlserver级联更新和删除c#调用存储过程返回值

整理一下级联更新和删除 c#调用返回值 use master  go  IF exists(select 1 from sysdatabases where name='temp') BEGIN       DROP DATABASE temp END create database temp

ZhangPeng的博客 532

c# mysql 时间戳_C#更新SQLServer中TimeStamp字段(时间戳)的方法

public partial class Form1 : Form{private SqlConnection mCnn = null;private long TimeStampValue;public Form1(){InitializeComponent();mCnn = new SqlConnection();mCnn.ConnectionString = "Data Source=192...

weixin_42160376的博客 488

c# update Oracle带参数 写法

刚刚从MySql/MSSQL数据库转到Oracle,用C#调用时一直更新不成功 ,后来发现是传参数格式不正确的问题。 Oracle里的command 要在参数名前用冒号:标注。SqlServer和MySQL都是用@。 见http://www.codeproject.com/Questions/618582/ORA-00936-missing-expression public ...

bangzhi6544的博客 243

C# SqlBulkCopy sqlserver 批量插入和更新数据

/// <summary> /// SqlBulkCopy 帮助类 /// </summary> public static class SqlBulkCopyHelper { /// <summary> /// 本地认证评估SQL //...

weixin_30699831的博客 1241

C#更新SQLServer中的TimeStamp字段(时间戳)

public partial class Form1 : Form     {         private SqlConnection mCnn = null;         private long TimeStampValue;         public Form1()         {             InitializeComponent();

limlimlim的专栏 1万+

SqlBulkCopy php,C# SqlBulkCopy sqlserver 批量插入和更新数据

/// ///SqlBulkCopy 帮助类/// public static classSqlBulkCopyHelper{/// ///本地认证评估SQL/// private const string CreateTemplateSql= @"[Id] [int] NOT NULL,[DisabilityCardId] [nvarchar](50) NOT NULL,[PartId] ...

weixin_34832809的博客 311

C#批量更新sql server数据数据

批量更新有两种策略: 第一种方式:拼接所有更新字符串,在数据库一次性执行,这样减少数据更新时频繁的连接断开数据库。 第二种方式:把要更新数据写入数据库全局临时,然后利用sql语句更新,最后把原中不存在的数据获取到再批量写入。 以下是第二种方式的实现。 该方式中有投机取巧的嫌疑,但是确实能对在单机大批量更新的操作有很大帮助。 1、tableName是要更新数据库的名称。 2...

藿香正气片博客 7763

股神人工智能股票预测系统V3.1

股神--人工智能股票预测系统是专门为股票投资者开发的一套全新的基于人工智能技术的股票趋势预测软件平台。该软件以基因演化算法(GP)为内核对股票交易历史数据进行自动建模和学习,挖掘出股票交易大数据中隐藏的行为规律,并以此为依据对下一个股票日的最高价和最低价的涨跌趋势进行预测分析。该软件能够帮助您了解何时进入股市,何时退出股市,并在最佳的时机买进或卖出股票,从而获取最大的利润和收益。支持6种典型的股票类别:上证指数、上证A股、上证B股、深证指数、深证A股和深证B股。精确的股票预测信息(如上涨、下跌或持平)和买卖推荐信息(如买入、卖出、持股以及买入价、卖出价等)。基因演化算法参数支持用户自定义,默认设置为种群大小:30,杂交概率:0.8,变异概率:0.1,最大运行代数:1000。支持批量操作,如股票批量评测、模型批量训练、股票批量预测、批量增加股票代码、批量添加/撤销我的股票池等。对大多数股票而言,最高价与最低价的涨跌趋势预测准确度达60%-80%;对部分股票而言,预测准确度最高可达90%。仅需简单的操作即可完成股票评测、智能选股、模型训练以及股票预测等功能。系统主界面支持从云数据库和本地数据库自动更新最优股票预测信息。支持流行的微软Windows操作系统,如Windows 98/Me/2000/XP/Vista/7。

上一篇: 每月第几周的算法
下一篇: 断续时间求总和
siegebaoniu
博客等级 码龄18年 50粉丝 22原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值