1

I want to import Excel chart into my SQL Server database by select it by dialog box and automatically save it to the SQL Server table + I want to generate the record ID by the sub that I made.

The sub that generates the MembersID is:

Public MyNewMembersID As Integer
Public Sub Code_Members()
    Dim dt As New DataTable
    Dim da As New SqlDataAdapter("select max(MembersID) from Members", Con)
    da.Fill(dt)
    If IsDBNull(dt(0)(0)) = True Then
        MyNewMembersID = 1
    Else
        MyNewMembersID = dt(0)(0) + 1
    End If

This is my code that errors with a message that MembersID must not be NULL:

Imports System.IO
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.Configuration

Public Class MembersImport
    Private Sub MembersImport_FilePath_Button_Click(sender As Object, e As EventArgs) Handles MembersImport_FilePath_Button.Click
        MembersImport_OpenFileDialog.ShowDialog()
    End Sub

    Private Sub MembersImport_ImportFile_Button_Click(sender As Object, e As EventArgs) Handles MembersImport_ImportFile_Button.Click
        If MembersImport_FilePath_TextBox.Text = "" Then
            MsgBox("Please Select File Excel", MsgBoxStyle.RetryCancel, "File Not Found")
            MembersImport_FilePath_Button.PerformClick()
        Else
            Dim con_excel As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & MembersImport_FilePath_TextBox.Text & "';Extended Properties=""Excel 12.0 Xml;HDR=Yes""")
            con_excel.Open()
            Dim query_excel As String = "Select * from [Sheet1$]"
            Dim cmd As OleDbCommand = New OleDbCommand(query_excel, con_excel)
            Dim rd As OleDbDataReader
            Dim con_sql As New SqlConnection()
            Dim con_sqlDB As String = "Data Source=(localdb)\ProjectsV13;Initial Catalog=Euro_SQL_Server;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
            con_sql.ConnectionString = con_sqlDB
            con_sql.Open()
            Using BulkCopy As SqlBulkCopy = New SqlBulkCopy(con_sql)
                BulkCopy.DestinationTableName = "dbo.Members"
                Try
                    rd = cmd.ExecuteReader
                    BulkCopy.WriteToServer(rd)
                    rd.Close()
                    con_sql.Close()
                    MsgBox("تم الاسترداد بنجاح")
                    MembersImport_FilePath_TextBox.Text = ""
                Catch ex As Exception
                    MsgBox(ex.ToString)
                End Try
            End Using
            Load_Members()
            Me.Close()
        End If
    End Sub

    Private Sub MembersImport_OpenFileDialog_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles MembersImport_OpenFileDialog.FileOk
        MembersImport_FilePath_TextBox.Text = MembersImport_OpenFileDialog.FileName
    End Sub
End Class

And this is my table structure:

CREATE TABLE [dbo].[Members] 
(
    [MembersID] INT NOT NULL,
    [MembersName] NVARCHAR(MAX) NULL,
    [MembersGender] NVARCHAR(MAX) NULL,
    [MembersPhone] NVARCHAR(MAX) NULL,
    [MembersAddress] NVARCHAR(MAX) NULL,
    [MembersMembershiping] BIT NULL,
    [MembersMembershipNum] NVARCHAR (MAX) NULL,
    [MembersMembershipValidityFrom] DATE NULL,
    [MembersMembershipValidityTo] DATE NULL,
    [MembersSubscriberSystem] NVARCHAR(MAX) NULL,
    [MembersCarBrand] NVARCHAR(MAX) NULL,
    [MembersCarModel] NVARCHAR(MAX) NULL,
    [MembersCarManufacturingYear] NVARCHAR(MAX) NULL,
    [MembersCarNum] NVARCHAR(MAX) NULL,
    [MembersChassisNum] NVARCHAR(MAX) NULL,
    [MembersCarColor] NVARCHAR(MAX) NULL,
    [MembersNotes] NVARCHAR(MAX) NULL,
    [ActionBy] NVARCHAR(MAX) NULL,

    PRIMARY KEY CLUSTERED ([MembersID] ASC)
);

So all I need is to import the data that is in the Excel with generated MembersID into the SQL Server database

3
  • In English You Do NOT Capitalize Each And Every Word ....
    – marc_s
    Commented Nov 5, 2017 at 9:16
  • 2
    Also: you should use appropriate string lengths - don't just make everything NVARCHAR(MAX) because you're too lazy to think about what proper length the strings should be. The MAX types are great - IF you really need up to 2 billion characters - but a phone number?!?!?!? Really !?!?!??!? Or gender?? C'mon - you can do better than this!
    – marc_s
    Commented Nov 5, 2017 at 9:17
  • @marc_s loool u r right man i did't relisez it till now by u,, i'm still noob here :D so forgive my low knowledge :V
    – GMCadiom
    Commented Nov 5, 2017 at 9:40

2 Answers 2

0

You don't generate the ID in the code. You generate the ID by making the ID field an identity field.

6
  • yeah that what i got it from here link now how i can make it ??
    – GMCadiom
    Commented Nov 5, 2017 at 15:55
  • i have fixed it by add on the sql table code IDENTITY(1,1) and now became like that [MembersID] INT NOT NULL PRIMARY KEY IDENTITY(1,1),
    – GMCadiom
    Commented Nov 5, 2017 at 16:16
  • Google "change field to identity sql server".
    – vbjay
    Commented Nov 5, 2017 at 16:32
  • Change to bigint and not int.
    – vbjay
    Commented Nov 5, 2017 at 16:33
  • thank you very much <3 i have googled it and found what i need that i need to add IDENTITY(1,1) and i will try to change INT to bigint as u said but for now it working stable as i need <3
    – GMCadiom
    Commented Nov 7, 2017 at 17:32
0

That's a lot of MAX! I guess you are taking it to the MAX. Anyway, can you try it like this? The script below should do what you want.

Public Sub ImportDataFromExcel(excelFilePath As String) 
        'declare variables - edit these based on your particular situation 
        Dim ssqltable As String = "Table1" 
        ' make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have    different 
        Dim myexceldataquery As String = "select student,rollno,course from [sheet1$]" 
        Try 
            'create our connection strings 
            Dim sexcelconnectionstring As String = (Convert.ToString("provider=microsoft.jet.oledb.4.0;data source=") & excelFilePath) + ";extended properties=" + """excel 8.0;hdr=yes;""" 
            Dim ssqlconnectionstring As String = "Data Source=SAYYED;Initial Catalog=SyncDB;Integrated Security=True" 
            'execute a query to erase any previous data from our destination table 
            Dim sclearsql As String = Convert.ToString("delete from ") & ssqltable 
            Dim sqlconn As New SqlConnection(ssqlconnectionstring) 
            Dim sqlcmd As New SqlCommand(sclearsql, sqlconn) 
            sqlconn.Open() 
            sqlcmd.ExecuteNonQuery() 
            sqlconn.Close() 
            'series of commands to bulk copy data from the excel file into our sql table 
            Dim oledbconn As New OleDbConnection(sexcelconnectionstring) 
            Dim oledbcmd As New OleDbCommand(myexceldataquery, oledbconn) 
            oledbconn.Open() 
            Dim dr As OleDbDataReader = oledbcmd.ExecuteReader() 
            Dim bulkcopy As New SqlBulkCopy(ssqlconnectionstring) 
            bulkcopy.DestinationTableName = ssqltable 
            While dr.Read() 
                bulkcopy.WriteToServer(dr) 
            End While 
            dr.Close() 
            oledbconn.Close() 
            Label1.Text = "File imported into sql server." 
            'handle exception 
        Catch ex As Exception 
        End Try 
    End Sub
3
  • my code almost like yours .. my problem is on the MembersID which it is primary key and can't be null even on the excel there's no MembersID columns and i want to generate it automatic while importing the sheet to the database
    – GMCadiom
    Commented Nov 5, 2017 at 15:55
  • I looked online for a way to handle this and didn't come up with much at all. I understand that MembersID can't be null. Can you simply kick those records out? Anything that comes through as a NULL should not be a valid record anyway, right. Or, once everything is in your table, simply run a delete query against those NULLS. DELETE FROM YourTable WHERE MembersID IS NULL;
    – ASH
    Commented Nov 7, 2017 at 2:58
  • 1
    thank you very much for your attention <3 now i have fixed it by add on the sql table code IDENTITY(1,1) and now became like that [MembersID] INT NOT NULL PRIMARY KEY IDENTITY(1,1),
    – GMCadiom
    Commented Nov 7, 2017 at 17:34

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.