各位大神帮我看下这还有别的方法转换类型吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.OleDb;
namespace ConsoleApp_cXTest
{
class Program
{
private const string CONN_STR = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\AccessData2007\myDate1.accdb";
static void Main(string[] args)
{
string sql = "select * from myTable";
if (AddObjectIntoTable(sql)>0)
{
Console.WriteLine("成功添加数据!");
}
else
{
Console.WriteLine("数据添加失败!");
}
Console.ReadKey();
}
public static int AddObjectIntoTable(string sql)
{
int n = 0;
DataTable m_Table = new DataTable();
OleDbConnection oledb_cn = null; ;
try
{
oledb_cn = new OleDbConnection(CONN_STR);
oledb_cn.Open();
OleDbDataAdapter oledb_da = new OleDbDataAdapter(sql, oledb_cn);
oledb_da.Fill(m_Table);
DataRow newRow = m_Table.NewRow();
//循环添加列数据到newRow中
for (int i = 0; i < m_Table.Columns.Count; i++)
{
Console.Write("请输入 "+m_Table.Columns[i].ColumnName + ":"); //提示输入的列名称
string str = Console.ReadLine();
Type type = m_Table.Columns[i].DataType; //获取列的数据类型
//数据类型转换,没有找到别的方法,只有用这最笨的方法
//哪们大神能给出别的方法不
switch(type.Name)
{
case "Int32":
newRow[i] = str != "" ? int.Parse(str) : 0;
break;
case "String":
newRow[i] = str;
break;
case "Double":
newRow[i] = str != "" ? double.Parse(str) : 0;
break;
}
}
m_Table.Rows.Add(newRow);
OleDbCommandBuilder oledb_cmb = new OleDbCommandBuilder(oledb_da);
n=oledb_da.Update(m_Table);
}
catch (Exception e)
{
Console.WriteLine("Eorr:" + e.Message);
}
finally
{
if(oledb_cn.State==ConnectionState.Open)
{
oledb_cn.Close();
}
}
return n;
}
}
}