Import Excel Data to Relational Tables at MySQL

后端 未结 3 708
自闭症患者
自闭症患者 2021-01-06 10:37

I have three tables at my MySQL database. First one is cities, second one is towns and third one is districts. Every town has many districts. My table details:

3条回答
  •  粉色の甜心
    2021-01-06 10:47

    A rough example of using MySQL with Excel and ADO. Suitable connection strings can be got from http://connectionstrings.com

    Dim cn As New ADODB.Connection
    Dim sFile As String, scn As String, sSQL As String
    Dim MySQLConnectionString As String
    
    ''It is probably better to use the name of the workbook
    ''eg C:\Docs\Cities.xls
    sFile = ActiveWorkbook.FullName
    
    ''Access 2003 or less
    scn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sFile _
        & ";Extended Properties=""Excel 8.0;HDR=Yes"";"
    cn.Open scn
    
    MySQLConnectionString = "ODBC;Driver={MySQL ODBC 5.1 Driver};Server=localhost;" _
    & "Database=mydatabase;User=myuser;Password=mypass;Option=3;"
    
    ''Fields (columns) are case sensitive
    ''Insert cities from sheet1, you can also use a named range, 
    ''include or a range
    sSQL = "INSERT INTO [" & MySQLConnectionString & "].Cities (Id,City) " _
    & "SELECT Id,City FROM [Sheet$] WHERE Id Not In " _
    & "(SELECT Id FROM [" & MySQLConnectionString & "].Cities )"
    
    cn.Execute sSQL, dbFailOnError
    

提交回复
热议问题