Dim findTheseVals(1) As Object
' Set the values of the keys to find.
Dim myDAgn As New SqlDataAdapter
findTheseVals(0) = pDivisionno
findTheseVals(1) = pGNe
sqlCon.Open()
Dim myDSGN As New DataSet
myDAgn.SelectCommand = New SqlCommand("SELECT * FROM Villages", sqlCon)
myDAgn.Fill(myDSGN, "Villages")
myPrimaryKey(0) = myDSGN.Tables("Villages").Columns("DivisionNo")
myPrimaryKey(1) = myDSGN.Tables("Villages").Columns("VillageSin")
myDSGN.Tables("Villages").PrimaryKey = myPrimaryKey
Dim myRow As DataRow
myRow = myDSGN.Tables("Villages").Rows.Find(findTheseVals)
If Not (myRow Is Nothing) Then
isExistsVi = True
VIid = myRow.Item("VillageID")
Else
isExistsVi = False
End If
sqlCon.Close()
pGNe is Parameter
VillageSin is a Column and contain UNICODE Data
When compile following error erised
"These Columns dont' Currently have unique values"
How can search unicode data from Dataset
How to correct above c
It seems like this line
myDSGN.Tables("Villages").PrimaryKey = myPrimaryKey
is the one with the error "These Columns dont' Currently have unique values" because your data is running afoul of the unique requirement on primary keys.
All this means is that you can't use Find. This has nothing to do with SQL Server or Unicode data.
instead get rid of this line myDSGN.Tables("Villages").PrimaryKey = myPrimaryKey and use .Select instead
Related
I have a VB form and a combobox linked to a datasource.
The database has two tables Position (SLOT, ID_WH) and Warehouse (ID_WH, WH_NAME).
The combobox is linked to the warehouse, and it shows the WH_NAME.
I need to get the ID_WH to insert into the Position table.
The code is:
WH_CB.DisplayMember = "Warehouse" 'Column name
WH_CB.ValueMember = "ID_WH" 'Column name2
'ADD INFO TO Position (SLOT)
Dim Remove_space_start As String = SLOT_TXT.Text
Dim CharStart() As Char = {" "}
Dim Stringstart As String = Remove_space_start.TrimStart(CharStart)
Dim CharEnd() As Char = {" "}
Dim StringEnd As String = Stringstart.TrimEnd(CharEnd)
Try
objconnection.Open()
cmd.Connection = objconnection
cmd.CommandText = "InsertDataIntoPosition"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("SLOT", StringEnd)
cmd.Parameters.AddWithValue("ID_WH", WH_CB.SelectedValue)
cmd.ExecuteNonQuery()
MessageBox.Show("sucess")
'Refresh DATAGRID
dgv_slot.DataSource = Nothing
dgv_slot.Refresh()
Dim str As String = "select * from Position"
Using cmd As New SqlCommand(str, objconnection)
Using da As New SqlDataAdapter(cmd)
Using newtable As New DataTable
da.Fill(newtable)
dgv_slot.DataSource = newtable
End Using
End Using
End Using
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." &
ex.Message,
"Insert Records")
Finally
objconnection.Close()
End Try
I've tried to show the whcb with a messagebox, and it shows the ID_WH, but trying to insert data into the table I get the error:
System.Data.SqlClient.SqlException: 'Conversion failed when converting the nvarchar value 'Armazem4 ' to data type int.'
Any help?
It's solved, thank you very much.
I had the same field name (with different types) in different tables, So I was forcing the wrong one to get the information.
After I corrected that, its working fine.
In need of your opinions. Currently developing an application in VB.NET.
I have a text file which contains more than one thousand rows. Each rows contains the data needed to be inserted into the database. A sample of a row is as follows:
0001--------SCOMNET--------0.100---0.105
At first glance, one might figured that each column was separated with a tab but actually each column was separated by blank spaces (I used '-' to denote as blank spaces because somehow could not get SO text editor to show the blank spaces).
The first column is defined by
Substring(0, 12) which is the data [0001--------]
second column
Substring(12, 12) in which the data is [SCOMNET-----]
third column is
Substring(24, 8) in which the data is [---0.100]
and last column is
Substring(32, 8) in which the data is [---0.105]
My initial though is to extract the lines for the text file and stored in as a list of strings, then while looping, do the separation of the each string item in the list with the SubString() function and insert it one by one until the end of the list. But this will no doubt takes time.
In my scenario, how can I take advantage of the SqlBulkCopy? Or if there is any other ways to approach this for a faster insert? Say;
open file
start loop
read line
separate each column in the line with substring
save in a DataTable
end loop
BCP(DataTable)
This includes a method that may be a more efficient way of reading your text file.
Sub readFixWidthTextFileIntoSqlTable()
Dim sqlConn As New SqlConnection("Connection String Goes Here")
sqlConn.Open()
Dim sqlComm As New SqlCommand
sqlComm.Connection = sqlConn
sqlComm.CommandType = CommandType.Text
sqlComm.CommandText = "INSERT INTO YourTableNameHere VALUES(#Field1, #Field2, #Field3, #Field4)"
sqlComm.Parameters.Add("#Field1", SqlDbType.Text)
sqlComm.Parameters.Add("#Field2", SqlDbType.Text)
sqlComm.Parameters.Add("#Field3", SqlDbType.Text)
sqlComm.Parameters.Add("#Field4", SqlDbType.Text)
Using IFReader As New FileIO.TextFieldParser(FileNameWithPath)
IFReader.TextFieldType = FileIO.FieldType.FixedWidth
IFReader.SetFieldWidths(12, 12, 8, 8)
While Not IFReader.EndOfData
Dim fields As String() = IFReader.ReadFields
sqlComm.Parameters("#Field1").Value = fields(0)
sqlComm.Parameters("#Field2").Value = fields(1)
sqlComm.Parameters("#Field3").Value = fields(2)
sqlComm.Parameters("#Field4").Value = fields(3)
sqlComm.ExecuteNonQuery()
End While
End Using
sqlConn.Close()
End Sub
You've got it pretty much right. This approach is one that I take a lot. Here's a bit of sample code to get you started. It is ONLY an example, there's absolutely no validation or and no consideration for Primary Keys on the table. If you want to review your question with more details of the structure of the destination table then I can make this example much more specific.
Read_File:
Dim sFileContents As String = ""
Using sRead As New StreamReader("e:\ExampleFile.txt")
sFileContents = sRead.ReadToEnd
End Using
Dim sFileLines() As String = sFileContents.Split(vbCrLf)
Connect_To_DB:
Dim sqlConn As New SqlConnection
sqlConn.ConnectionString = "Data Source=YourServerName;Initial Catalog=YourDbName;Integrated Security=True"
sqlConn.Open()
Setup_DataTable:
Dim ExampleTable As New DataTable
ExampleTable.Load(New SqlCommand("Select Top 0 * From Example_Table", sqlConn).ExecuteReader)
'This is not absolutely necessary but avoids trouble with NOT NULL columns (like keys)'
For Each dcColumn As DataColumn In ExampleTable.Columns : dcColumn.AllowDBNull = True : Next dcColumn
Save_To_DataTable:
For Each sLine In sFileLines
Dim ExampleRow As DataRow = ExampleTable.NewRow
ExampleRow("First_Column_Name") = sLine.Substring(0, 12).TrimEnd
ExampleRow("Second_Column_Name") = sLine.Substring(12, 12).TrimEnd
ExampleRow("Third_Column_Name") = sLine.Substring(24, 8).TrimEnd
ExampleRow("Fourth_Column_Name") = sLine.Substring(32, 8).TrimEnd
ExampleTable.Rows.Add(ExampleRow)
Next
Update_Database:
If ExampleTable.Rows.Count <> 0 Then
Dim sqlBulk As SqlBulkCopy = New SqlBulkCopy(sqlMvConnection)
sqlBulk.DestinationTableName = "Example_Table"
sqlBulk.WriteToServer(ExampleTable)
End If
Disconnect_From_DB:
sqlConn.Close()
Also, as commented on above and if you have access to it SSIS will do this in a jiffy.
VB.NET 2012, ADO.NET, SQL Server 2014
I setup a parameterized query that works well. I essentially read records from a DataTable that comes from a different source than my SQL Server. It's small enough that I elected to read record by record and build a query and hit the SQL Server for a match.
However I am having trouble getting a match when one of my fields is supposed to be matched for a null. I know a record exist because I can look at it in SQL Server directly and see it. With my parameterized query somehow the null is being translated improperly. I tried manually replacing the parameter #EngSerialNo with DBNull.Value and still doesn't work. Almost seems like I need two different queries depending if my DataTable value is null.
sqQry.AppendLine("SELECT CityCode,CarNum,RegNum,Event,EngSerialNum)")
sqQry.AppendLine("FROM [MyDB].[dbo].[Events]")
sqQry.AppendLine("WHERE (CityCode=#City AND CarNum=#CarNo AND RegNum=#RegNo AND Event=#Event AND EngSerialNum=#EngSerialNo)") 'this looks for a value in EngSerialNo
'sqQry.AppendLine("WHERE (CityCode=#City AND CarNum=#CarNo AND RegNum=#RegNo AND Event=#Event AND EngSerialNum IS NULL)") 'this looks for a Null in EngSerialNo
Dim cmd As New SqlCommand
With cmd
.Connection = connMyDb
.CommandType = CommandType.Text
.CommandText = sqQry.ToString
'cycle through each DataRow in the DataTable and check for returns
Dim total As Integer = 0
For Each row As DataRow In dtMain.Rows
.Parameters.Clear()
.Parameters.AddWithValue("#City", row.Item("City"))
.Parameters.AddWithValue("#CarNo", row.Item("CarNo"))
.Parameters.AddWithValue("#RegNo", row.Item("RegNo"))
.Parameters.AddWithValue("#Event", row.Item("Event"))
.Parameters.AddWithValue("#EngSerialNo", row.Item("EngSerialNo")) 'how do I get this to look for a null value when the DataTable contains a null value?
Dim rowsAffected As Integer = .ExecuteNonQuery()
total += rowsAffected
Next row
End With
Update: I ended up creating a dynamic SQL for every DataRow. Basically for each DataRow I check key fields for NULL or an actual value and create the appropriate SQL command text. I have 4 fields that could contain a NULL but for sake of simplicity I only demonstrated one here. I think the developer can follow the example to create their own query.
Dim cmd As New SqlCommand
With cmd
.Connection = connMyDb
.CommandType = CommandType.Text
'cycle through each DataRow in the DataTable and check for returns
Dim total As Integer = 0
For Each row As DataRow In dtMain.Rows
.CommandText = BuildSql(row)
.Parameters.Clear()
.Parameters.AddWithValue("#City", row.Item("City"))
.Parameters.AddWithValue("#CarNo", row.Item("CarNo"))
.Parameters.AddWithValue("#RegNo", row.Item("RegNo"))
.Parameters.AddWithValue("#Event", row.Item("Event"))
.Parameters.AddWithValue("#EngSerialNo", row.Item("EngSerialNo"))
Dim rowsAffected As Integer = .ExecuteNonQuery()
total += rowsAffected
Next row
End With
Private Function BuildSql(ByVal dr As DataRow) As String
Dim sqQry As New StringBuilder
sqQry.AppendLine("SELECT CityCode,CarNum,RegNum,Event,EngSerialNum)")
sqQry.AppendLine("FROM [MyDB].[dbo].[Events]")
If dr.Item("EngSerialNo") Is DBNull.Value Then
sqQry.AppendLine("WHERE (CityCode=#City AND CarNum=#CarNo AND RegNum=#RegNo AND Event=#Event AND EngSerialNum IS NULL)") 'this looks for a Null in EngSerialNo
Else
sqQry.AppendLine("WHERE (CityCode=#City AND CarNum=#CarNo AND RegNum=#RegNo AND Event=#Event AND EngSerialNum=#EngSerialNo)") 'this looks for a value in EngSerialNo
End If
Return sqQry.ToString
End Function
In SQL you can't compare null values, i.e. EngSerialNum = null always evaluates to false, even if the value in the field is null.
Either you can create the query dynamically so that you use is null to match the null values, or you can use an expression like this:
((EngSerialNum is null and #EngSerialNo is null) or EngSerialNum = #EngSerialNo)
So, Access database has two columns 1st is seller name (SELLER) and second is it's code (CODE). Access database is database with all SELLER CODEs.
DGV is populated from other source and consists of some of CODEs from Access database.
DGV has one column with codes.
I would like to create and populate new column (SELLERNAME) in DGV with SELLER names based on DGV codes and Access database CODEs.
I am going to give an example since it's hard for me to explain this better :
DGV : Column 0, 1st value = 0055, in Access database code 0055 corresponds to the name John
so I would like to put name "John" in DGV Column1, 1st value, nest to "0055" and so on
Here is my code so far :
DataGridView1.Columns.Add("SELLERNAME", "SELLERNAME") '1
Dim cn As OleDb.OleDbConnection
Dim cmd As OleDb.OleDbCommand
Dim odr As OleDb.OleDbDataReader
Dim strSQL As String
cn = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\SCodes.MDB")
strSQL = "SELECT SELLER, CODE FROM SCBASE"
cn.Open()
cmd = New OleDb.OleDbCommand(strSQL, cn)
odr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While odr.Read
For i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).Cells(1).Value = odr.GetValue(1).ToString()
Next
Loop
I don't know what to do next after line For i As Integer = 0 To DataGridView1.Rows.Count - 1.
EDIT :
I think I am close but I need help with one line of code :
Using sqlconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\SCodes.mdb")
Using sqlcmd = New OleDbCommand("Select SELLER, CODE From SCBASE Where CODE = #CODE ", sqlconn)
sqlcmd.Parameters.AddWithValue("#CODE ", DataGridView1.Rows(i).Cells(0).Value) 'HOW TO ADD THIS LINE IN LOOP BELOW
sqlconn.Open()
Dim result = sqlcmd.ExecuteReader()
Do While (result.Read())
For i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).Cells(1).Value = (result("DOBAVLJAC"))
Next
Loop
End Using
End Using
I had no success with a trial and error. I am trying to put this line sqlcmd.Parameters.AddWithValue("#CODE ", DataGridView1.Rows(i).Cells(0).Value) in loop below but I am getting all sorts of error.
Yes, you are very close. You just need to .Add the Parameter outside the loop and then set its .Value inside the loop like this
Using sqlconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\SCodes.mdb")
sqlconn.Open()
Using sqlcmd = New OleDbCommand("Select SELLER, CODE From SCBASE Where CODE = ?", sqlconn)
sqlcmd.Parameters.Add("?", OleDbType.VarWChar, 255)
sqlcmd.Prepare()
For i As Integer = 0 To DataGridView1.Rows.Count - 1
sqlcmd.Parameters(0).Value = DataGridView1.Rows(i).Cells(0).Value
Using result = sqlcmd.ExecuteReader()
If result.Read() Then
DataGridView1.Rows(i).Cells(1).Value = result("SELLER")
End If
End Using
Next
End Using
End Using
I need to import records from a comma delimited CSV file into an existing table in SQL Server R2 database using Visual Basic .Net 2010. Existing records in the table are to be deleted prior to import. I have been able to create an in-memory temporary DataTable and populate the records from CSV file using TextFieldParser. I have checked it by binding the in-memory DataTable to a DataGridView. But I am clueless in the second part i.e. how to insert records into the SQL table from the in-memory DataTable.
I have done the following:
`Dim TextFileReader As New TextFieldParser("C:\csvtosql\StockVB\VFPFiles\ExpSysusers.csv")
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(",")
Dim TextFileTable As DataTable = Nothing
Dim Column As DataColumn
Dim Row As DataRow
Dim UpperBound As Int32
Dim ColumnCount As Int32
Dim CurrentRow As String()
CurrentRow = TextFileReader.ReadFields() ' Ignore the header
While Not TextFileReader.EndOfData
Try
CurrentRow = TextFileReader.ReadFields()
If Not CurrentRow Is Nothing Then
''# Check if DataTable has been created
If TextFileTable Is Nothing Then
TextFileTable = New DataTable("TextFileTable")
''# Get number of columns
UpperBound = CurrentRow.GetUpperBound(0)
''# Create new DataTable
For ColumnCount = 0 To UpperBound
Column = New DataColumn()
Column.DataType = System.Type.GetType("System.String")
Column.ColumnName = "Column" & ColumnCount
Column.Caption = "Column" & ColumnCount
Column.ReadOnly = True
Column.Unique = False
TextFileTable.Columns.Add(Column)
Next
End If
Row = TextFileTable.NewRow
For ColumnCount = 0 To UpperBound
Row("Column" & ColumnCount) = CurrentRow(ColumnCount).ToString
Next
TextFileTable.Rows.Add(Row)
End If
Catch ex As Exception
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
TextFileReader.Dispose()
DataGridView1.DataSource = TextFileTable
`
Can anybody please help/guide me??
I tried the following code to read the records from the DataTable and insert into the SQL Table. But it seems that only the first record is being added.
For Each TextFileTableDataRow As DataRow In TextFileTable.Rows
Dim Column0 As String = TextFileTableDataRow("Column0")
Dim Column1 As String = TextFileTableDataRow("Column1")
Dim Column2 As Int16 = TextFileTableDataRow("Column2")
Dim Column3 As Boolean = TextFileTableDataRow("Column3")
Dim strSqlQry As String = "INSERT INTO Personnel (Operator,OpPassword,SecurityLevel,Active) VALUES (#Operator,#OpPassword,,#SecurityLevel,#Active)"
Dim SqlconnectionString As String = gcconnect
Using connection As New SqlClient.SqlConnection(SqlconnectionString)
Dim cmd As New SqlClient.SqlCommand(strSqlQry, connection)
' create command objects and add parameters
With cmd.Parameters
.AddWithValue("#Operator", Column0)
.AddWithValue("#OpPassword", Column1)
.AddWithValue("#SecurityLevel", Column3)
.AddWithValue("#LoggedOn", Column7)
End With
Dim adapter As New SqlClient.SqlDataAdapter()
adapter.InsertCommand = cmd
'--Update the original SQL table from the datatable
Dim iRowsInserted As Int32 = adapter.Update(TextFileTable)
End Using
Next
I am getting the following error:
"Violation of PRIMARY KEY Constraint 'PK_Personnel'. Cannot insert duplicate key in object 'dbo.Personnel'."