Ricardo Goncalves Posted February 12, 2016 at 10:54 AM Report Share #593398 Posted February 12, 2016 at 10:54 AM Boas, Estou com um problema ao tentar passar a informação de um TXT para uma base de dados em SQLServer. Está-me a gerar o erro: An unhandled exception of type 'System.NullReferenceException' occurred in WindowsApplication5.exe Additional information: A referência de objecto não foi definida como uma instância de um objecto. na linha " Dim data As String() = line.Split(New Char()" Alguem me pode ajudar? Em baixo está o codigo que estou a usar. Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim fileName As String = "C:\teste_cliente.txt" Using conn As New SqlConnection("Data Source=localhost;Initial Catalog=teste;Persist Security Info=True;User ID=sa;Password=1234") Dim query As String = "INSERT INTO Customer (CustomerID,createdate,OrganizationName,FederalTaxID,hralt,ZoneID,PaymentID,TenderID,SalesmanID,EntityFiscalStatusID,DtAlt) VALUES('9999',convert(nvarchar(10),getdate(),120)+' 00:00:00.000',@a, @b, ((((((datepart(hour,getdate())*60)+datepart(MINUTE,getdate()))*60)+datepart(SECOND,getdate()))*999)+datepart(ms,getdate()))*1.0/86313600,'1','1','1','1','1' ,convert(nvarchar(10),getdate(),120)+' 00:00:00.000')" Using cmd As New SqlCommand(query, conn) For Each line As String In ReadingFile(fileName) Dim data As String() = line.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries) cmd.Parameters.AddWithValue("@a", Integer.Parse(data(0))) cmd.Parameters.AddWithValue("@b", Integer.Parse(data(1))) Try cmd.ExecuteNonQuery() Catch ex As Exception MessageBox.Show(ex.Message) Exit Try End Try Next End Using End Using End Sub Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T target = value Return value End Function Private Function ReadingFile(path As String) As IEnumerable(Of String) Using sr As New StreamReader(path) Dim line As String While (InlineAssignHelper(line, sr.ReadLine())) IsNot Nothing Yield Return line End While End Using End Function Private Sub [Yield](p1 As Object) Throw New NotImplementedException End Sub End Class Link to comment Share on other sites More sharing options...
Soulsick Posted February 14, 2016 at 04:38 PM Report Share #593498 Posted February 14, 2016 at 04:38 PM Boas, já experimentaste usar Dim data As String() = line.Split(",", StringSplitOptions.RemoveEmptyEntries) em vez do que tens? Cumps Link to comment Share on other sites More sharing options...
Ricardo Goncalves Posted February 15, 2016 at 11:20 AM Author Report Share #593529 Posted February 15, 2016 at 11:20 AM (edited) Boas SoulSick Desde já obrigado pela resposta mas o limitador tem que estar sempre entre "{ }" senão não dá . Alguém têm mais alguma solução ? Estou farto de dar voltas a cabeça e não consigo preceber o porqué o erro entretanto modifiquei um pouco o código mas o erro continua o mesmo. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim fileName As String = "C:\teste\teste_cliente.csv" Using conn As New SqlConnection("Data Source=localhost;Initial Catalog=teste;Persist Security Info=True;User ID=sa;Password=1234") Dim query As String = "INSERT INTO Customer (CustomerID,createdate,OrganizationName,FederalTaxID,hralt,ZoneID,PaymentID,TenderID,SalesmanID,EntityFiscalStatusID,DtAlt) VALUES(@a,convert(nvarchar(10),getdate(),120)+' 00:00:00.000',@b, @c, ((((((datepart(hour,getdate())*60)+datepart(MINUTE,getdate()))*60)+datepart(SECOND,getdate()))*999)+datepart(ms,getdate()))*1.0/86313600,'1','1','1','1','1' ,convert(nvarchar(10),getdate(),120)+' 00:00:00.000')" Using cmd As New SqlCommand(query, conn) Using sr As StreamReader = New StreamReader(fileName) Dim line As String line = sr.ReadLine() While (line <> Nothing) Console.WriteLine(line) line = sr.ReadLine() End While Dim data As String() = line.Split(New Char() {","}, StringSplitOptions.RemoveEmptyEntries) cmd.Parameters.AddWithValue("@a", Integer.Parse(data(0))) cmd.Parameters.AddWithValue("@b", Integer.Parse(data(1))) cmd.Parameters.AddWithValue("@c", Integer.Parse(data(2))) Try cmd.ExecuteNonQuery() Catch ex As Exception MessageBox.Show(ex.Message) Exit Try End Try End Using End Using End Using End Sub Edited February 15, 2016 at 11:22 AM by Ricardo Goncalves Link to comment Share on other sites More sharing options...
Ricardo Goncalves Posted February 15, 2016 at 11:57 AM Author Report Share #593532 Posted February 15, 2016 at 11:57 AM Mesmo usando só Dim data As String() = line.Split(";") Dá o mesmo erro: An unhandled exception of type 'System.NullReferenceException' A referência de objecto não foi definida como uma instância de um objecto. Link to comment Share on other sites More sharing options...
Ricardo Goncalves Posted February 15, 2016 at 12:46 PM Author Report Share #593533 Posted February 15, 2016 at 12:46 PM (edited) Já consegui ultrapassar o erro anterior modificando o código para : Dim fileName As String = "C:\teste\teste_cliente.csv" Using conn As New SqlConnection("Data Source=localhost;Initial Catalog=teste;Persist Security Info=True;User ID=sa;Password=1234") Dim query As String = "INSERT INTO Customer (CustomerID,createdate,OrganizationName,FederalTaxID,hralt,ZoneID,PaymentID,TenderID,SalesmanID,EntityFiscalStatusID,DtAlt) VALUES('9999',convert(nvarchar(10),getdate(),120)+' 00:00:00.000',@a, @b, ((((((datepart(hour,getdate())*60)+datepart(MINUTE,getdate()))*60)+datepart(SECOND,getdate()))*999)+datepart(ms,getdate()))*1.0/86313600,'1','1','1','1','1' ,convert(nvarchar(10),getdate(),120)+' 00:00:00.000')" Using cmd As New SqlCommand(query, conn) conn.Open() For Each line In File.ReadAllLines(fileName) Dim parts As String() = line.Split(New Char() {";"c}) cmd.Parameters.AddWithValue("@a", (parts(0))) cmd.Parameters.AddWithValue("@b", (parts(1))) Next Try cmd.ExecuteNonQuery() Catch ex As Exception MessageBox.Show(ex.Message) Exit Try End Try End Using End Using Mas agora tenho um novo erro mas a nivel de sql esta a dar o seguinte erro: The Variable name '@a' has already been declared. Varibales names must be unique withibn a query batch or stored procedure. Edited February 15, 2016 at 12:46 PM by Ricardo Goncalves Link to comment Share on other sites More sharing options...
Solution Soulsick Posted February 15, 2016 at 01:10 PM Solution Report Share #593536 Posted February 15, 2016 at 01:10 PM Boas ainda bem que já resolve o problema anterior 😄 para isto podes declarar os parametros antes do For Each comando.Parameters.Add("@a") e depois durante o for each comando.Parameters.Item("@a").Value = "valor" em alternativa, podes colocar assim que também deve dar Dim parts As String() = line.Split(New Char() {";"c}) cmd.Parameters.AddWithValue("@a", (parts(0))) cmd.Parameters.AddWithValue("@b", (parts(1))) cmd.Parameters.Clear Cumps Link to comment Share on other sites More sharing options...
Ricardo Goncalves Posted February 15, 2016 at 03:32 PM Author Report Share #593542 Posted February 15, 2016 at 03:32 PM Boas Soulsick, Mais uma vez muito obrigado pela ajuda. usei assim: cmd.Parameters.Clear() cmd.Parameters.AddWithValue("@a", (parts(0))) cmd.Parameters.AddWithValue("@b", (parts(1))) cmd.Parameters.AddWithValue("@c", (parts(2))) Tive que colocar o Clear primeiro, mas foi mesmo falta de pensar porque se estava a declarar a variável não a podia declarar novamente. Fica Bem... Link to comment Share on other sites More sharing options...
Soulsick Posted February 15, 2016 at 04:30 PM Report Share #593544 Posted February 15, 2016 at 04:30 PM Ainda bem que conseguiste resolver 🙂 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now