Home php教程 php手册 谈谈数据从sql server数据库导入mysql数据库的体验(原创)

谈谈数据从sql server数据库导入mysql数据库的体验(原创)

Jun 21, 2016 am 09:09 AM
mysql nbsp quot server

mysql|server|数据|数据库|原创

因工作需要,要将存放在sql server数据库中的数据全部导入到mysql数据库中,在网上搜集相关资料,找到两种方法,现在分别谈谈对他们的看法。

第一种是安装mysql ODBC,利用sql server的导出功能,选择mysql数据源,进行数据的直接导出,这种方法很简便,但是针对实际应用有很多弊端,最主要体现就是数据类型问题,首先,sql server数据库中
的ntext,image等数据类型的数据无法直接写入到mysql数据库中,据说只要稍加改动就可以,可惜偶这只菜鸟还没想到如何改动,其次,因为偶在mysql中的数据库设计中将时间都设成int型(保存的是时间戳),所以在数据导过来后,就会出现冲突,再次,这种方法生成的mysql数据表的字段类型都不很合适,所以此种方法我觉得不能提倡。

第二种是利用php或asp脚本来实现数据的导入功能,这种方法需要编写程序,但灵活性大,操作也不是那么困难,一切都尽在你的掌握之中,现简单介绍一下该方法
前提条件是你的mysql环境已经搭建好了,先建好目标数据库,再将所有的表结构用sql语句生成,现在万事具备,只缺数据了。

可以通过下面的php脚本来实现sql server中mydb数据库的user表中数据向mysql中mydb数据库导入

$cnx = odbc_connect('web', 'admin', '123456');//'web'是sqlserver中mydb的数据源名,'admin'是访问mydb的用户名,'123456'是访问mydb的密码
$cur= odbc_exec( $cnx, 'select *  from user' );//打开sql server中mydb数据库的user表
$num_row=0;
$conn=mysql_pconnect("localhost","root","123456");// 连接mysql
@mysql_select_db('mydb',$conn) or

die("无法连接到数据库,请与管理员联系!");//打开mysql的mydb数据库
while( odbc_fetch_row( $cur ))            //从sql server的mydb库中的user表逐条取出数据,如果对数据进行选择,可在前面的select语句中加上条件判断
{
  $num_row++;
  $field1 = odbc_result( $cur, 1 );   // 这里的参数i(1,2,3..)指的是记录集中的第i个域,你可以有所选择地进行选取,fieldi得到对应域的值,然后你可以对fieldi进行操作
  $field2 = odbc_result( $cur, 2 );   
  $field3 = odbc_result( $cur, 3 );   
  $field4 = odbc_result( $cur, 4 );   
  $field5 = odbc_result( $cur, 5 );   
  $field6 = odbc_result( $cur, 6 );   
  $field5 = timetoint($field5);    //这里是对sql server中的datetime类型的字段进行相应转换处理,转换成我所需要的int型   
  $querystring = "insert into user
                  (id,name,username,password,recdate)
                values('$field1','$field2','$field3','$field4','$field5')" ;

  mysql_query($querystring,$conn);
}

function timetoint($str){
  $arr1=split(" ",$str);
  $datestr=$arr1[0];
  $timestr=$arr1[1];
  $arr_date=split("-",$datestr);
  $arr_time=split(":",$timestr);
  $year=$arr_date[0];
  $month=$arr_date[1];
  $day=$arr_date[2];
  $hour=$arr_time[0];
  $minute=$arr_time[1];
  $second=$arr_time[2];
  $time_int=mktime($hour,$minute,$second,$month,$day,$year);
  return $time_int;
}
?>

将该段脚本存成sql.php,在服务器上执行,就可以将服务器上sql server中mydb数据库的user表中的数据导入到mysql中mydb数据库的user表中去。其他表的操作与此雷同,就不赘述了。

下面再介绍一下asp脚本实现sql server中mydb数据库的数据向mysql中mydb数据库导入
set conn=server.createobject("adodb.connection")
conn.open 'web', 'admin', '123456' // 'web'是sqlserver中mydb的数据源名,'admin'是访问mydb的用户名,'123456'是访问mydb的密码
set rs=server.createobject("adodb.recordset")
sql="select ID,name,username,password,datediff(s,'1970-01-01 00:00:00',recdate)-8*3600,reid,filename,fileContentType,filevalue from senddate" //这条sql语句实现了将datetime类型的recdate字段转化成unix时间戳的int型

rs.open sql,conn,1,3
set conn1=server.createobject("adodb.connection")
conn1.open "myoa","root","q1-d6=7?"
i=1
do while not rs.eof
  field1 = rs(0)   
  field2 = rs(1)   
  field3 = rs(2)   
  field4 = rs(3)   
  field5 = rs(4)   
  sql1 = "insert into user(ID,name,username,password,recdate)        

values("&field1&",'"&field2&"','"&field3&"','"&field4&"',"&field5&")"

conn1.execute sql1
rs.movenext
i=i+1
loop
rs.close
set rs=nothing
conn.close
set conn=nothing
conn1.close
set conn1=nothing

%>

以上两个是分别采用php脚本和asp脚本对user表的数据进行由sql server到mysql的导入其间我采用2种回避的方法来避免ntext,image类型数据的传递,一种是将ntext字段改为nvarchar(4000),因为实际情况,原始数据中该字段的数据长度都未超过4000个字,所以并没有出现数据截断,另一个手段是将image类型数据取出来写到文件中,以文件形式保存,将文件路径存到数据库中,方法见下:

function makeattach(fileContentType,filevalue,i)
    select case fileContentType
        case "application/msword"
            ext="doc"

        case "application/vnd.ms-excel"
            ext="exl"
            
        case "application/vnd.ms-powerpoint"
            ext="pps"
            
        case "application/x-rar-compressed"
            ext="rar"
            
        case "application/x-zip-compressed"
            ext="zip"
            
        case "image/gif"
            ext="gif"
            
        case "image/pjpeg"
            ext="jpg"
            
        case "text/plain"
            ext="txt"
            
        case else
            ext="x"
            
    end select
    if ext"x" then
        set fso=server.createobject("FileSystemObject")
        fName="attech"&i&"."&ext
        Dir="d:\attach\"
        If fso.FileExists(Dir & fName) Then fso.deletefile Dir & fName
        If fName"" AND NOT fso.FileExists(Dir & fName) Then
            Set strm1=Server.CreateObject("ADODB.Stream")
            strm1.Open
            strm1.Type=1 'Binary
            strm1.Write filevalue
            strm1.SaveToFile Dir & fName,2
            Set strm1=Nothing
        end if
        makeattach=fName
    end if
end function

这个函数有3个输入参数,第一个是文件的contentType,第二个是文件的二进制数值,第三个是个可以区别文件名的变量,先根据contentType确定所存文件的后缀名,然后就是将二进制数值保存成指定文件名的文件,并将文件名作为输出参数返回,将返回的参数作为数据写到mysql的数据库中保存。
时间匆忙,先总结到这里,希望这些文字能对有需要的人有些帮助,少走些弯路,感谢您的阅读。:)



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: The Ease of Data Management for Beginners MySQL: The Ease of Data Management for Beginners Apr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to create navicat premium How to create navicat premium Apr 09, 2025 am 07:09 AM

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

How to create a new connection to mysql in navicat How to create a new connection to mysql in navicat Apr 09, 2025 am 07:21 AM

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

How to execute sql in navicat How to execute sql in navicat Apr 08, 2025 pm 11:42 PM

Steps to perform SQL in Navicat: Connect to the database. Create a SQL Editor window. Write SQL queries or scripts. Click the Run button to execute a query or script. View the results (if the query is executed).

Navicat connects to database error code and solution Navicat connects to database error code and solution Apr 08, 2025 pm 11:06 PM

Common errors and solutions when connecting to databases: Username or password (Error 1045) Firewall blocks connection (Error 2003) Connection timeout (Error 10060) Unable to use socket connection (Error 1042) SSL connection error (Error 10055) Too many connection attempts result in the host being blocked (Error 1129) Database does not exist (Error 1049) No permission to connect to database (Error 1000)

See all articles