Importing MS Access to MS SQL Server - sql-server

Currently trying to update an SQL Server database from an Access db, it works importing new records but fails on when I reimport the file and there is a duplicate - in looking for it to insert the row if it's not there (working), but skip if it already exists. The first column has the primary key set.
Dim table As DataTable = New DataTable
Dim accConnection As New OleDb.OleDbConnection(
"Provider=Microsoft.JET.OLEDB.4.0; Data Source='C:\Tester.mdb';User Id=admin; Password=;")
Dim sqlConnection As New SqlClient.SqlConnection(
"Data Source=10.75.24.94;Initial Catalog=CTData;User ID=sql;Password=")
Try
'Import the Access data
accConnection.Open()
Dim accDataAdapter = New OleDb.OleDbDataAdapter(
"SELECT * FROM Import_test", accConnection)
accDataAdapter.Fill(table)
accConnection.Close()
'Export to MS SQL
For Each row As DataRow In table.Rows
row.SetAdded()
Next
sqlConnection.Open()
Dim sqlDataAdapter As New SqlClient.SqlDataAdapter(
"SELECT * FROM Import_test", sqlConnection)
Dim sqlCommandBuilder As New SqlClient.SqlCommandBuilder(sqlDataAdapter)
sqlDataAdapter.InsertCommand = sqlCommandBuilder.GetInsertCommand()
sqlDataAdapter.UpdateCommand = sqlCommandBuilder.GetUpdateCommand()
sqlDataAdapter.DeleteCommand = sqlCommandBuilder.GetDeleteCommand()
sqlDataAdapter.Update(table)
sqlConnection.Close()
Catch ex As Exception
If accConnection.State = ConnectionState.Open Then
accConnection.Close()
End If
If sqlConnection.State = ConnectionState.Open Then
sqlConnection.Close()
End If
MessageBox.Show("Import failed with error: " &
Environment.NewLine & Environment.NewLine &
ex.ToString)
End Try
The error I'm presented with is:
Violation of Primary key. Cannot insert duplicate key in object.

I think you can remove VB from the equation (I like to make things as simple as possible, without over-simplifying it). You have several options available.
INSERT INTO Table
SELECT * FROM #Table xx
WHERE NOT EXISTS (SELECT 1 FROM Table rs WHERE rs.id = xx.id)
Or . . .
DELETE FROM Table
WHERE (ID NOT IN (SELECT MAX(ID) AS Expr1
FROM Table
AS Table_1 GROUP BY NAME,ADDRESS,CITY,STATE,ZIP,PHONE,ETC.))
There are a lot of other ways to handle this as well. Is you need to incorporate VB, you can do something like this.
Dim cmd As New OleDbCommand
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\your_path\DB.accdb")
Dim queryResult As Integer
Dim sqlQRY As String = "SELECT COUNT(*) AS FROM ESRRegister WHERE ID = '" & IDtxt.Text & "'"
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.Text
If queryResult > 0 Then
cmd.CommandText = "insert into ESRRegister (Dt,ID)VALUES ('" & Dttxt.Text & "' , '" & IDtxt.Text & "')"
queryResult = cmd.ExecuteScalar()
MsgBox("Added Successfuly")
Else
MessageBox.Show("Already Exists!", "ALI ENTERPRISES", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If

Related

Search Another Type Text SQL Server VB.Net

I have a problem with search: how do I search our language text from SQL query and which type data I select
Dim cmd As New SqlCommand
cmd.Connection = cn
cmd.CommandText = "SELECT * FROM Table_12 WHERE m='" & "دولت خان" & "'"
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count() > 0 Then
TextBox2.Text = table.Rows(0)(1).ToString()
MessageBox.Show("Record found!")
Else
MessageBox.Show("Record not found!")
Keep your database objects local so you can control that they are closed and disposed. A single Using...End Using block handles this for you.
You can pass your connection string directly to the constructor of the connection and pass the command text and connection directly to the constructor of the command.
Always use parameters to avoid Sql Injection. The value concatenated to an sql command string is potentially executable. Parameter values are not.
Private Sub OpCode()
Dim dt As New DataTable
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("SELECT * FROM Table_12 WHERE m= #m;", cn)
cmd.Parameters.Add("#m", SqlDbType.NVarChar, 50).Value = "دولت خان"
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count() > 0 Then
TextBox2.Text = dt.Rows(0)(1).ToString()
MessageBox.Show("Record found!")
Else
MessageBox.Show("Record not found!")
End If
End Sub
Search with like clause for unicode in column m and show column o:
cmd.CommandText = "SELECT o FROM Table_12 WHERE m like N'%" & "دولت خان" & "%'"

Running SQL Server query in VB.NET

How would I create a query that returns a column in the database? The SQL select statement is easy. I'm having issues with the VB side.
SELECT UserNO
FROM UserTable
WHERE UserID = user;
I need to then get that UserNO and pass it to another T-SQL stored procedure. How would I go about running a SELECT query and getting the results back in Visual Basic?
Attached is some of my code. The code below adds the user to the DB however the UserNo (INTEGER) is automatically generated by SQL Server as the INSERT statement is run in the insert stored procedure, so I need to pull the UserNO after the user is created.
Public conwd As SqlConnection = New SqlConnection("Server=*****;Database=*****;User Id=****;Password=****")
Public conwp As SqlConnection = New SqlConnection("Server=*****;Database=*****;User Id=****;Password=****")
Dim cmdP As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'", conwp)
Dim cmdD As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'", conwd)
conmp.Open()
conmd.Open()
cmdP.ExecuteNonQuery()
cmdD.ExecuteNonQuery()
The Using..End Using blocks close and dispose of your data objects that might contain unmanaged code. The Parameters help prevent SQL injection.
Private Sub OPCode2()
Dim newID As Integer
Dim sql = "Insert Into UserTable (User) Values (#User); Select SCOPE_IDENTITY();"
Using cn As New SqlConnection("Your Connection String")
Using cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#User", SqlDbType.NVarChar).Value = "Brian Weaver"
cn.Open()
newID = CInt(cmd.ExecuteScalar)
End Using
End Using
'Use the newID in your next command
UserStoredProcedure(newID)
End Sub
Private Sub UseStoredProcedure(id As Integer)
Dim sql = "InsertSomeUserInfo" 'the name of your stored procedure
Using cn As New SqlConnection("Your Connection String")
Using cmd As New SqlCommand(sql, cn)
cmd.CommandType = CommandType.StoredProcedure
'whatever parameter names and types your stored procedure uses
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = id
cmd.Parameters.Add("#Salary", SqlDbType.Decimal).Value = 50000
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
Dim cmdP As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'" + "; SELECT CAST(scope_identity() AS int", conwp)
Dim userNo as Integer = cmdP.ExecuteScalar()
ExecuteScalar retrieves the first line of the result

How to count tell if data already exist in a sql table using VB.net

I have a table that looks like thisTable When I use this code it works fine
Private Sub CountData()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=LVAPP; Initial Catalog=CFLineTracker;Persist Security Info=True;User ID=CFLineAdmin;Password=aaonunit#1"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT COUNT(*) FROM ItemDetails where ItemMasterId = " & IMID & ""
RD = cmd.ExecuteScalar
Label5.Text = RD
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
End Sub
But when I try to run this code I get an exception
Private Sub CountData()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Data Source=LVAPP; Initial Catalog=CFLineTracker;Persist Security Info=True;User ID=CFLineAdmin;Password=aaonunit#1"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT COUNT(*) FROM ItemDetails where Serial Number = " & SN & ""
RDSN = cmd.ExecuteScalar
Label5.Text = RDSN
End Sub
The SQL Exception is:
Additional information: An expression of non-boolean type specified in
a context where a condition is expected, near 'Number'.
I'm using SQL SERVER 2008 R2 VB.net 2013

Insert with parameters

I should change all queries to use parameters to protect app from SQL injection.
Current insert sample which works is:
If Len(ExecuteQuery("INSERT INTO ICE_Order_Details(Order_ID, Product_ID, License_Type_ID, Maintenance_ID, Qty, Shareit_Running_No, Price, Total) VALUES(" & OrderID & ", " & ProductID & ", " & LicenseTypeID & ", " & MaintenanceID & ", " & Val(Request("QUANTITY")) & ", " & Val(Request("RUNNING_NO")) & ", " & Price & ", " & Price * Val(Request("QUANTITY")) & ")")) > 0 Then
'SendBadRequest "Could not run insert Order detail query"
Can you help me to write parametric query instead of this?
I tried a lot of ways to do this but here is below last one.
Dim ConnString As New SqlConnection("Provider=SQLOLEDB.0;Data Source=something;Initial Catalog=something;Persist Security Info=True;User ID=something;Password=something")
Dim SqlString As String ="INSERT INTO ICE_Order_Details(Order_ID, Product_ID, License_Type_ID, Maintenance_ID, Qty, Shareit_Running_No, Price, Total) VALUES(#OrderID, #ProductID, #LicenseTypeID, #MaintenanceID, #Qty, #RunningNo, #Price, #Total)"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#OrderID", OrderID)
cmd.Parameters.AddWithValue("#ProductID", ProductID)
cmd.Parameters.AddWithValue("#LicenseTypeID", LicenseTypeID)
cmd.Parameters.AddWithValue("#MaintenanceID", MaintenanceID)
cmd.Parameters.AddWithValue("#Qty", Val(Request("QUANTITY")))
cmd.Parameters.AddWithValue("#RunningNo", Val(Request("RUNNING_NO")))
cmd.Parameters.AddWithValue("#Price", Price)
cmd.Parameters.AddWithValue("#Total", Price * Val(Request("QUANTITY")))
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Edit: It still doesn't work. Here is my current code for adding parameters:
cmd.Parameters.Add("#OrderID", SqlDbType.Int).Value = OrderId
cmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = ProductID
cmd.Parameters.Add("#LicenseTypeID", SqlDbType.Int).Value = LicenseTypeID
cmd.Parameters.Add("#MaintenanceID", SqlDbType.Int).Value = MaintenanceID
cmd.Parameters.Add("#Qty", SqlDbType.Int).Value = Int32.Parse(Request("QUANTITY"))
cmd.Parameters.Add("#RunningNo", SqlDbType.Int).Value = Int32.Parse(Request("RUNNING_NO"))
cmd.Parameters.Add("#Price", SqlDbType.Money).Value = Money.Parse(Price)
cmd.Parameters.Add("#Total", SqlDbType.Money).Value = Money.Parse(Price * Int32.Parse(Request("QUANTITY")))
Edit: I changed my insert query to test only insert with parameters. But it don't work
Dim ConnString As String = ConfigurationManager.ConnectionStrings("DB_Connection_String0").ConnectionString
Dim SqlString As String ="INSERT INTO Unsubscribed(E-Mail) VALUES(#E-Mail)"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#E-Mail", SqlDbType.nvarchar).Value = "testiram#obrisime.sada"
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
here is error which i got (it marked 'As') if I change connection string it show error on next 'As' in code with same error message
Microsoft VBScript compilation error '800a0401'
Expected end of statement
/Test.asp, line 8
Dim ConnString As String =
ConfigurationManager.ConnectionStrings("DB_Connection_String0").ConnectionString
---------------^
Finally I found solution for this
Thanks all for help!
here is code below which work fine
<%
Dim oConn, oCmd, ds, sql
p1 = "test"
p2 = "test"
p3 = "test"
ds = "Provider=SQLOLEDB.1;Data Source=___;Initial Catalog=___;User ID=___;Password=___;"
sql = "INSERT INTO table (prop1, prop2, prop3) VALUES (?,?,?)"
Set oConn=Server.CreateObject("ADODB.Connection")
oConn.Open ds
Set oCmd = Server.CreateObject("ADODB.Command")
oCmd.ActiveConnection = oConn
oCmd.CommandText = sql
oCmd.CommandType = 1
oCmd.Parameters(0) = p1
oCmd.Parameters(1) = p2
oCmd.Parameters(2) = p3
oCmd.Execute()
oConn.close
Set oConn=nothing
%>
it is better to use sqlhelper class file by microsoft which i think is best for this cause and is relatively easy to use and shortens code by much. e.g
in save click event it will go like this
sqlParameter[] parem=
{
new sqlparameter("#value1"urcontrol.text),
new sqlparameter("#value2"urcontrol.text),
new sqlparameter("#value3"urcontrol.text)
};
sqlhelper.executenonquery (connectionstring,commandtype.storeprocedure,"ProcedureName",parem);
rest will be handled automatically by sqlhelper class file

SQL delete query on non key column

I'm new to the SQL query language and I'm trying to figure out how to delete a row (in a SQL DB table) with a non key ID column value using vb.net. For example in the table TEST below:
ID Name
1 x
2 y
3 z
I have a windows form that the user selects the Name value, however when I run my code it says
Cannot convert varchar "y" to int.
Here is my code attempt:
Dim sConnectionString As String
sConnectionString = "Data Source=" + serverName + ";Initial Catalog=" + dbName + ";Integrated Security=SSPI;"
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim cmd As New SqlCommand
cmd.Connection = objConn
cmd.CommandText = "DELETE FROM TEST WHERE Name = y"
cmd.ExecuteNonQuery()
Thank you!
If your Name column is of type varchar you need to enclose the value in single quotes
cmd.CommandText = "DELETE FROM TEST WHERE Name = 'y'"
A complete answer to your question will be:
Dim sConnectionString As String
sConnectionString = "Data Source=" + serverName + _
";Initial Catalog=" + dbName + _
";Integrated Security=SSPI;"
Dim objConn As SqlConnection
Using(objConn = new SqlConnection(sConnectionString)
objConn.Open()
Dim cmd As New SqlCommand
cmd.Connection = objConn
cmd.CommandText = "DELETE FROM TEST WHERE Name = #name"
cmd.Parameters.AddWithValue("#name", txtName.Text)
cmd.ExecuteNonQuery()
End Using
I'm supposing that your user insert the name to delete in a textbox and you pass this value to a parametrized query. The use of parametrized query will save you from the hassle to handle quoting problems and from Sql Injection Attacks
If you do this you will be deleting all rows WHERE Name = y and you probably don't want to do that.
You should use the name in the UI but pass the ID to SQL.
If you really do want to delete ALL rows with that name then put quotes around the y, as without them it's looking for a column named y:
DELETE FROM TEST WHERE Name = 'y'
cmd.CommandText = "DELETE FROM TEST WHERE Name = y";
instead you can use this one
cmd.CommandText = "DELETE FROM TEST WHERE ID = " + idValue;
here the 'idValue' is the ID that u take from the user
OR OTHER WISE
cmd.CommandText = "DELETE FROM TEST WHERE Name = 'y'";

Resources