如何在c#中用逗号分割字符串并保存在数据库中 [英] how to split string with comma in c# and save in the database

查看:258
本文介绍了如何在c#中用逗号分割字符串并保存在数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

datagridview中的以下数据如下;



日期名称



1/3/2012 Ram,suresh





数据库中我想保存如下;



日期名称

1/3/2012 Ram

1/3/2012 suresh





如何用逗号分割字符串并保存在数据库中。



用于将两个数据保存到数据库中如何使用csharp 。



请注意它是windows应用程序。

The below datas in datagridview as follows;

Date Name

1/3/2012 Ram,suresh


in the database i want to save as follows;

Date Name
1/3/2012 Ram
1/3/2012 suresh


how to split the string with comma and save in the database.

for saving the two datas into the database how can i do using csharp.

note it is windows application.

推荐答案

我认为最好将你的字符串分成三个元素,并提取日期:
I believe it's best to split your string into three elements, and extract the date:
private string test = @"1/3/2012 Ram,suresh";

private char[] splitChars = new[] {',', ' '};

private void testData()
{
    var splitString = test.Split(splitChars);

    if(splitString.Length(!= 3)) // throw error ?

    DateTime date;

    if (DateTime.TryParse(splitString[0], out date))
    {
        // you have a valid date
    }
    else
    {
        // throw error ?
    }

    // update database
    // date splitString[1] => database
    // date splitString[2] => database


按照以下步骤操作:



1.你必须拆分字符串','使用C#并存储在字符串数组中。

2.使用带字符串数组的foreach循环将数据插入数据库。



例如:



Follow the below steps:

1. you have to split the string by ',' using C# and store in string array.
2. Use foreach loop with the string array insert the data into database.

For Example:

string strValue = "Ram,suresh";
string[] strArray = strValue.Split(',');

foreach (object obj in strArray)
{
//your insert query
}


Datetime strDate;
strDate="1/3/2012";
string strText="Ram,suresh";
string []strArr=strText.split(',')

for(i=0;strArr.Length;i++)
{
strSQl='insert into tablename(datet,textvalue) values ('"+strDate+"','"+ strArr[i].Tostring() +"');'   

}





请忽略这些情况并使用参数化查询。



更新,对不起我的错误,谢谢



谢谢



Please ignore the cases and use parameterized query.

updated, sorry for my mistake, thanks

Thanks


这篇关于如何在c#中用逗号分割字符串并保存在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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