前几天在黑马论坛上遇到一个网友求手机IP地址的数据,我便回复,网上如果找不到的话可以加我QQ,今晚下班回来,打开QQ给他传过去~结果让他想不到,用不了,因为我在网下下的是Access的数据库,而他用的是Sql Server数据库,然后我就引用了前几天所学的知识~些了一小段程序,把Access数据库里的数据导入到Sql Server,虽然代码不够简洁,但还是顺利的完成啦~哈哈,希望网友给予改善
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;//导入Access数据库的命名空间
using System.Data.SqlClient;
namespace 把Access书库导入Sql_server
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\mobile.mdb;Jet OLEDB:Database Password=123;Persist Security Info=False";//连接Access数据库的字符串
using (OleDbConnection conStr = new OleDbConnection(connectionString))
{
conStr.Open();//打开数据
using (OleDbCommand com = conStr.CreateCommand())
{
com.CommandText = "select * from list";
using (OleDbDataReader reader = com.ExecuteReader())
{
//string code = Convert.ToString(reader.GetString(reader.GetOrdinal("code")));
string sqlConStr = @"Data Source=HP-PC\SQLEXPRESS;Initial Catalog=login;Integrated Security=True";
using (SqlConnection sqlCon = new SqlConnection(sqlConStr))
{
sqlCon.Open();
using (SqlCommand sqlCmd = sqlCon.CreateCommand())
{
while (reader.Read())//读取数据库里的数据
{
string oleNum = Convert.ToString(reader.GetString(reader.GetOrdinal("num")));
string oleCode = Convert.ToString(reader.GetString(reader.GetOrdinal("code")));
string oleCity = Convert.ToString(reader.GetString(reader.GetOrdinal("city")));
string oleCardtype = Convert.ToString(reader.GetString(reader.GetOrdinal("cardtype")));
sqlCmd .CommandText= "insert into T_mobile(Num,Code,City,Cardtype) values(@num,@code,@city,@cardtype)";
SqlParameter anum = new SqlParameter("num",oleNum);
SqlParameter bcode = new SqlParameter("code", oleCode);
SqlParameter ccity=new SqlParameter("city",oleCity);
SqlParameter dcardtype=new SqlParameter("cardtype",oleCardtype);
sqlCmd.Parameters.Add(anum);
sqlCmd.Parameters.Add(bcode);
sqlCmd.Parameters.Add(ccity);
sqlCmd.Parameters.Add(dcardtype);
sqlCmd.ExecuteNonQuery();
sqlCmd.Parameters.Clear();
}
}
}