I stored some function's names in an Access table, an I would like to execute them in vb.net, I can't find the way to do it, maybe someone know how to do it.
public sub KeyDatesProcess()
Dim sqlQuery As String
Dim cmd As OleDbCommand
Dim rs As OleDbDataReader
Dim listForStartDates As List(Of CriticalDates)
Dim listForFinishDates As List(Of CriticalDates)
Try
sqlQuery = "select * from wbs_l2"
cmd = New OleDbCommand With {
.Connection = connection,
.CommandText = sqlQuery
}
rs = cmd.ExecuteReader()
Do While rs.Read
Debug.Print(rs(0) & " " & rs(3))
listForStartDates = CallByName(rs(6).ToString) 'this field contains a function
listForFinishDates = CallByName(rs(7).ToString) 'this field contains a function
Loop
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Related
I can select the data from an Access database, but I tried many ways to INSERT INTO database. There is no error message, but it didn't insert the data.
Code:
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurDir() & "\fsDB1.accdb")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
conn.Open()
Dim CommandString As String = "INSERT INTO tblfile(stdUname,filePw,filePath,status) VALUES('" & userName & "','" & filePw & "','" & filePath & "','A')"
Dim command As New OleDbCommand(CommandString, conn)
Command.Connection = conn
Command.ExecuteNonQuery()
I just want a simple easy way to INSERT INTO an Access database. Is it possible because of the problem of Access database? I can insert this query by running query directly in Access.
Firstly I would check the database settings. If your app copies a new copy of the database each time you run it that would explain why you can select existing data and why your new data is not being saved (Well it is being saved, but the database keeps getting replaced with the old one). Rather set it up to COPY IF NEWER.
Further, you should ALWAYS use parameterized queries to protect your data. It is also is less error prone than string concatenated commands ans is much easier to debug.
Also, I recommend using a USING block to handle database connections so that your code automatically disposes of resources no longer needed, just in case you forget to dispose of your connection when you are done. Here is an example:
Using con As New OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
"Data Source = "
Dim sql_insert As String = "INSERT INTO Tbl (Code) " & _
"VALUES " & _
"(#code);"
Dim sql_insert_entry As New OleDbCommand
con.Open()
With sql_insert_entry
.Parameters.AddWithValue("#code", txtCode.Text)
.CommandText = sql_insert
.Connection = con
.ExecuteNonQuery()
End With
con.Close()
End Using
Here is an example where data operations are in a separate class from form code.
Calling from a form
Dim ops As New Operations1
Dim newIdentifier As Integer = 0
If ops.AddNewRow("O'brien and company", "Jim O'brien", newIdentifier) Then
MessageBox.Show($"New Id for Jim {newIdentifier}")
End If
Back-end class where the new primary key is set for the last argument to AddNewRow which can be used if AddNewRow returns true.
Public Class Operations1
Private Builder As New OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
}
Public Function AddNewRow(
ByVal CompanyName As String,
ByVal ContactName As String,
ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Dim Affected As Integer = 0
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName) VALUES (#CompanyName, #ContactName)"
cmd.Parameters.AddWithValue("#CompanyName", CompanyName)
cmd.Parameters.AddWithValue("#ContactName", ContactName)
cn.Open()
Affected = cmd.ExecuteNonQuery()
If Affected = 1 Then
cmd.CommandText = "Select ##Identity"
Identfier = CInt(cmd.ExecuteScalar)
Success = True
End If
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
End Class
I have a SQL Server 2008 express with a database and a table and using VB 2010 express.
I am trying to read from that table with sqldatareader, but I only one row in the datagridview with the column headers, no row with data.
What am I doing wrong? (I'm a newbe).
The connection string is :
Data Source=xxxxxxxxxx\SQLEXPRESS;Initial Catalog=Masteca_Inventory;Integrated Security=True
Dim searchStr As String = ""
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim sqlStr As String
Public bindingSource1 As New BindingSource()
connetionString = My.Settings.SQLconnSTR
sqlStr = "SELECT * FROM Piese WHERE " & searchStr 'searchStr is OK I fill it elsewhere
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sqlStr, sqlCnn)
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
Using sqlReader
Dim dTable As New DataTable
dTable.Load(sqlReader)
bindingSource1.DataSource = dTable
End Using
SearchReport.DataGridView1.DataSource = bindingSource1
'SearchReport is another form
sqlReader.Close()
sqlCmd.Dispose()
sqlCnn.Close()
SearchReport.Show()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
You are not reading the data as a group (you are fetching only one result).
You will need to adjust the code to use a While sqlReader.Read;
Example;
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
While sqlReader.Read()
Try
'Do the work needed
rowResult += sqlReader(0) 'This will contain the result script
Catch ex As Exception
'Catch exception
End Try
End While
Something like that should work (I have not tested the code but the concept is the same).
PS - I strongly suggest you adjust your script to add a Where clause and / or the columns needed (Select * is not a "good practice")
Hope this helps.
I am trying to pass gridview data into database. The problem I am having is that not all data in my gridview is entering the database. Doing a messagebox shows only name column is going in. Here is my code
Protected Sub Button2_Click1(sender As Object, e As EventArgs) Handles Button2.Click
Dim sc As StringCollection = New StringCollection
Dim field1 As String = String.Empty
Dim i As Integer = 0
Do While (i < GridView1.Rows.Count)
field1 = GridView1.Rows(i).Cells(0).Text
i = (i + 1)
Loop
' get the field to be Inserted
sc.Add(field1)
' add the field to be Inserted in the StringCollection
InsertRecords(sc)
' call method for insert and pass the StringCollection values
End Sub
Dim conn As MySqlConnection = New MySqlConnection("Server=****************;Database=******;Uid=*******;Pwd=****;allow user variables=true")
Dim sb As StringBuilder = New StringBuilder(String.Empty)
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO student(name, age, adress) VALUES ("
sb.AppendFormat("{0}'{1}' ", sqlStatement, item)
Next
sb.Append(")")
MsgBox(sb.ToString)
Try
conn.Open()
Dim cmd As MySqlCommand = New MySqlCommand(sb.ToString, conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg = (msg + ex.Message)
Throw New Exception(msg)
Finally
conn.Close()
End Try
End Sub
Don't concatenate strings to create a sql command but use parameters to primarily avoid sql-injection.
Const sqlStatement As String = "INSERT INTO student(name, age, adress) VALUES (?Pname,?Page,?Padress)"
Try
Using con = New MySqlConnection(connectionString)
con.Open()
For Each item In sc
Using cmd = New MySqlCommand(sqlStatement, con)
cmd.Parameters.AddWithValue("?Pname", item.Name)
cmd.Parameters.AddWithValue("?Page", item.Page)
cmd.Parameters.AddWithValue("?Padress", item.Padress)
cmd.ExecuteNonQuery()
End Using
Next
End Using
Catch ex As System.Data.SqlClient.SqlException
' log message '
Throw ' don't use throw new Exception or throw ex '
End Try
Note that i've used sc like a collection of a custom class with all needed properties. But even if that was not correct, it should give you an idea how it works.
I have a VB.Net app that should enable the user to import CSV file into the datagrid (which it does) and then update those rows to a table in Oracle.
Here is what I have so far but it doesn't seem to work neither throw an error.
Private Sub Update_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Update.Click
MsgBox("Saving...")
Dim table As New DataTable()
Dim BindingSource As New BindingSource()
BindingSource.DataSource = table
table.Columns.Add("ORDER_NO")
table.Columns.Add("LINE_ITEM_NO")
table.Columns.Add("CONTRACT")
table.Columns.Add("PART_NO")
table.Columns.Add("QTY_REQUIRED")
table.Columns.Add("QTY_PER_ASSEMBLY")
table.Columns.Add("RELEASE_NO")
table.Columns.Add("SEQUENCE_NO")
table.Columns.Add("ORDER_CODE")
table.Columns.Add("PART_OWNERSHIP")
Dim parser As New FileIO.TextFieldParser("C:\Documents and Settings\User\Desktop\solution.csv")
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True
parser.TrimWhiteSpace = True
parser.ReadLine()
Dim sConnectionString As String = "Data
Source=MYSERVER.COM;User ID=MYNAME;Password=MYPASSWD;"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOC_TAB(ORDER_NO,
LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY,
RELEASE_NO,SEQUENCE_NO,ORDER_CODE,PART_OWNERSHIP) VALUES (#ORDER_NO,
#LINE_ITEM_NO,#CONTRACT,#PART_NO,#QTY_REQUIRED,#QTY_PER_ASSEMBLY,#RELEASE_NO,#SEQUENCE_NO,#ORDER_CODE,#PART_OWNERSHIP)"
Using conn As New OracleClient.OracleConnection(sConnectionString)
Dim adapter As New OracleDataAdapter
Dim cmd As New OracleClient.OracleCommand()
cmd.Connection = conn
cmd.Connection.Open()
cmd.CommandText = strSql
adapter.InsertCommand = New OracleCommand(strSql, conn)
adapter.UpdateCommand = cmd
adapter.Update(table)
'--cmd.ExecuteReader()
cmd.Connection.Close()
MsgBox("Saved! Kindly check your Shop order!")
DataGridView1.DataSource = Nothing
End Using
End Sub
Now I have brought it down to inserting records in the table, but problem is it only parses the first column in the row.
So all suppose 6 columns in the table are updated with values from the first field in the CSV.
MsgBox("Saving...")
Dim parser As New FileIO.TextFieldParser("C:\Documents and Settings\nUser\Desktop\solution.csv")
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True
parser.TrimWhiteSpace = True
Dim i As Integer
For i = 0 To DataGridView1.RowCount - 1
Dim CurrentField = parser.ReadFields()
'--parser.ReadLine()
Dim sConnectionString As String = "Data Source=MYSERVER.COM;User ID=MYUSER;Password=MYPASSWD;"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOCT(ORDER_NO, LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY) VALUES (:ORDER_NO, :LINE_ITEM_NO,:CONTRACT,:PART_NO,:QTY_REQUIRED,:QTY_PER_ASSEMBLY)"
Using conn As New OracleClient.OracleConnection(sConnectionString)
Using cmd As New OracleClient.OracleCommand()
Dim adapter As New OracleDataAdapter
conn.Open()
cmd.Connection = conn
cmd.CommandText = strSql
cmd.Parameters.AddWithValue("ORDER_NO", CurrentField(i))
cmd.Parameters.AddWithValue("LINE_ITEM_NO", CurrentField(i))
cmd.Parameters.AddWithValue("CONTRACT", CurrentField(i))
cmd.Parameters.AddWithValue("PART_NO", CurrentField(i))
cmd.Parameters.AddWithValue("QTY_REQUIRED", CurrentField(i))
cmd.Parameters.AddWithValue("QTY_PER_ASSEMBLY", CurrentField(i))
cmd.CommandText = strSql
adapter.InsertCommand = New OracleCommand(strSql, conn)
adapter.UpdateCommand = cmd
'adapter.Update(table)
cmd.ExecuteNonQuery()
cmd.Connection.Close()
DataGridView1.DataSource = Nothing
End Using
End Using
Next
Never used oracle so please ignore me if I'm being stupid.
Have you tried conn.Connect() rather than cmd.Connection.Open()?
I don't understand the part of your code that create a DataTable and add columns.
It's not used anywhere, so is not related to your issue.
Let's look at code relating data connection
' If I remember well, the parameters in an oracle statement are prefixed by a ":"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOC_TAB(ORDER_NO," +
"LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY, " +
"RELEASE_NO,SEQUENCE_NO,ORDER_CODE,PART_OWNERSHIP) VALUES (:ORDER_NO, " +
":LINE_ITEM_NO,:CONTRACT,:PART_NO,:QTY_REQUIRED,:QTY_PER_ASSEMBLY, " +
":RELEASE_NO,:SEQUENCE_NO,:ORDER_CODE,:PART_OWNERSHIP)"
' Connection and Command are Disposable, so use `Using` around them
Using conn As New OracleClient.OracleConnection(sConnectionString)
Using cmd As New OracleClient.OracleCommand()
Dim adapter As New OracleDataAdapter
conn.Open()
cmd.Connection = conn
cmd.CommandText = strSql
' Now you need to add the parameters to your command
' One parameter for each column used in the insert statement
' I suppose that values for the paramenter are in the current line from your CSV
cmd.Parameters.Add("ORDER_NO", OracleType.VarChar).Value = parser[index_of_orderNumber_Text])
' .... other parameters to be added....
' Now you can execute the INSERT statement directly with your command
cmd.ExecuteNonQuery()
End Using
And, as last thing, the OracleClient namespace has been deprecated by Microsoft, so you should try to replace with ODP directly from Oracle.
I am new to this and had this question. Can I use SQLDataReader instead of a Recordset. I want to achieve the following result in an SQLDataReader.
Dim dbConn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sqlstr As String = "SELECT Name,Status FROM table1 WHERE id=" + item_id.Value.ToString
rs.Open(SQL, dbConn)
While Not rs.EOF
txtName.Text = rs.Fields.Item("Name").Value
ddlstatus.SelectedIndex = 1
rs.MoveNext()
End While
rs.Close()
rs = Nothing
dbConn.Close()
dbConn = Nothing
Can I replace recordset with SQLDataReader and if I can can you please show me the changes in code?
Its highly recommend that you use the using pattern:
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Using Con As New SqlConnection(sConnection)
Con.Open()
Using Com As New SqlCommand("Select * From tablename", Con)
Using RDR = Com.ExecuteReader()
If RDR.HasRows Then
Do While RDR.Read
txtName.Text = RDR.Item("Name").ToString()
Loop
End If
End Using
End Using
Con.Close()
End Using
You will have to swap out a few things, something similar to the following.
Here is an example, you will need to modify this to meet your goal, but this shows the difference.
I also recommend using a "Using" statement to manage the connection/reader. Also, a parameterized query.
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Dim objCommand As New SqlCommand
objCommand.CommandText = "Select * From tablename"
objCommand.Connection = New SqlConnection(sConnection)
objCommand.Connection.Open()
Dim objDataReader As SqlDataReader = objCommand.ExecuteReader()
If objDataReader.HasRows Then
Do While objDataReader.Read()
Console.WriteLine(" Your name is: " & Convert.ToString(objDataReader(0)))
Loop
Else
Console.WriteLine("No rows returned.")
End If
objDataReader.Close()
objCommand.Dispose()
Dim rdrDataReader As SqlClient.SqlDataReader
Dim cmdCommand As SqlClient.SqlCommand
Dim dtsData As New DataSet
Dim dtbTable As New DataTable
Dim i As Integer
Dim SQLStatement as String
msqlConnection.Open()
cmdCommand = New SqlClient.SqlCommand(SQLStatement, msqlConnection)
rdrDataReader = cmdCommand.ExecuteReader()
For i = 0 To (rdrDataReader.FieldCount - 1)
dtbTable.Columns.Add(rdrDataReader.GetName(i), rdrDataReader.GetFieldType(i))
Next
dtbTable.BeginLoadData()
Dim values(rdrDataReader.FieldCount - 1) As Object
While rdrDataReader.Read
rdrDataReader.GetValues(values)
dtbTable.LoadDataRow(values, True)
End While
dtbTable.EndLoadData()
dtsData.Tables.Add(dtbTable)
msqlConnection.Close()
Return dtsData