Read values from SQL Server database using vba - sql-server

i am using vba studio and would like to read some values from a sql database.
Here is my code:
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class log
Dim usuariovb As String
Dim passwordvb As String
Private Sub exe_log_Click(sender As Object, e As EventArgs) Handles exe_log.Click
usuariovb = txt_user.Text
passwordvb = txt_pw.Text
Dim sConnectionString As String = "Server=MXD071352\SQLEXPRESS; Database=CALLC; User Id=sa;Password=Kernmic1"
Using objConn As New SqlConnection(sConnectionString)
Dim comando As New SqlCommand("SELECT Contraseña from Usuarios WHERE Usuario = '" & usuariovb & "';", objConn)
objConn.Open()
Dim lector As SqlDataReader = comando.ExecuteReader()
Try
While lector.Read()
Console.WriteLine(String.Format("{0}, {1}", lector(0), lector(2)))
End While
Finally
lector.Close()
End Try
End Using
End Sub
Could you please help me, since I am not getting results

Related

Search by specific date in Access database with VB.net

I'm trying to search a date using DateTimePicker in an Access database and have the results show in the DataGridView but it doesn't work. No errors but it just doesn't show the database/results. Here's pictures of the database and the debugged form when it doesn't work in case they are of any use:
and here's my code:
Imports System.Data.OleDb
Public Class Form10
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Daily Sales.accdb;")
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
Dim dt1 As DateTime = DateTime.Parse(DateTimePicker1.Value)
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Table1] where [TDateField] = #" & dt1.ToString("MM/dd/yyyy"), connection)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd
DataGridView2.DataSource = da
connection.Close()
End Sub
Private Sub Form10_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "MM/dd/yyyy"
End Sub
End Class
Use the true date value of the datetime picker:
Dim dt1 As DateTime = DateTimePicker1.Value
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Table1] where [TDateField] = #" & dt1.ToString("yyyy'/'MM'/'dd") & "#", connection)

MultipleActiveResultSets for SQL Server and VB.NET application

I am trying to get multiple data sets from SQL Server using a VB.NET application. The problem that every time I try to execute the query,
I get this message:
Cannot change property 'ConnectionString'. The current state of the connection is open
Then I tried to fix it by enabling MARS
<connectionStrings>
<add name="ConString"
providerName="System.Data.SqlClient"
connectionString="Data Source=my-PC;Initial Catalog=Project;Persist Security Info=True; MultipleActiveResultSets=true;User ID=user;Password=*****" />
</connectionStrings>
This is my code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim obj, body
obj = TextBox1.Text
body = TextBox2.Text
For Each mail In getemail()
Send_mail(mail, obj, body, getattachment(mail))
Next
MsgBox("Traitement effectué")
End Sub
Function getemail() As List(Of String)
Dim strMailTo As New List(Of String)
Dim SQL As String = "Select EMail FROM [USER] WHERE EMail Is Not NULL And MatriculeSalarie Is Not NULL And [EMail] <> '' and EtatPaie = 3 and BulletinDematerialise = 1 "
Dim cmd As New SqlCommand
Dim sqLdr As SqlDataReader
Dim dr As DataRow
Try
ConnServer()
cmd.Connection = con
cmd.CommandText = SQL
Using sda As New SqlDataAdapter(cmd)
Using ds As New DataTable()
sda.Fill(ds)
sqLdr = cmd.ExecuteReader()
For i = 0 To ds.Rows.Count - 1
dr = ds.Rows(i)
strMailTo.Add(dr("EMail"))
Next
End Using
End Using
Return strMailTo
sqLdr.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
closeCon()
Return strMailTo
End Function
Function getattachment(email) As String()
Dim SQL As String = "Select MatriculeSalarie FROM [USER] WHERE [EMail]='" & email & "'"
Dim cmd As New SqlCommand
Dim sqLdr As SqlDataReader
ConnServer()
cmd.Connection = con
cmd.CommandText = SQL
Dim mat As String
mat = ""
Dim Dir As String = ConfigurationManager.AppSettings("path1").ToString
Dim file()
sqLdr = cmd.ExecuteReader()
While sqLdr.Read
mat = sqLdr.GetValue(sqLdr.GetOrdinal("MatriculeSalarie"))
End While
file = IO.Directory.GetFiles(Dir, mat.Substring(1) & "*.pdf")
sqLdr.Close()
Return file
End Function
If all you are going to do is show a message box in a Catch, don't do it in the database code. Let the error bubble up to the user interface code and put the Try around where the method is called.
Do not declare variables without a DataType. The button code with Option Infer on sets the type of obj and body.
Private ConStr As String = "Your connection string"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim obj = TextBox1.Text
Dim body = TextBox2.Text
Dim emails As New List(Of String)
Try
emails = getemail()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Error retrieving email list")
Exit Sub
End Try
For Each email In emails
Try
Send_mail(email, obj, body, getattachment(email))
Catch ex As Exception
MessageBox.Show(ex.Message, "Error getting attachments")
End Try
Next
MessageBox.Show("Traitement effectué")
End Sub
Parameters used by Sub and Function must have a DataType.
I don't know what you are doing here.
While sqLdr.Read
mat = sqLdr.GetValue(sqLdr.GetOrdinal("MatriculeSalarie"))
End While
Each iteration will overwrite the previous value of mat. I can only assume that you expect only a single value, in which case you can use ExecuteScalar to get the first column of the first row of the result set. Don't do anything with the data until after the connection is closed. Just get the raw data and close (End Using) the connection. Manipulate the data later.
Always use Parameters. Parameters are not treated as executable code by the database server. They are simply values. An example of executable code that could be inserted is "Drop table [USER];" where the value of a parameter belongs. Oops!
Function getemail() As List(Of String)
Dim SQL As String = "Select EMail FROM [USER]
WHERE EMail Is Not NULL
And MatriculeSalarie Is Not NULL
And [EMail] <> ''
And EtatPaie = 3
And BulletinDematerialise = 1;"
Dim dt As New DataTable
Using con As New SqlConnection("Your connection string"),
cmd As New SqlCommand(SQL, con)
con.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Dim strMailTo As New List(Of String)
strMailTo = (From row As DataRow In dt.AsEnumerable
Select row.Field(Of String)(0)).ToList
Return strMailTo
End Function
Function getattachment(email As String) As String()
Dim SQL As String = "Select MatriculeSalarie FROM [USER] WHERE [EMail]='" & email & "'"
Dim mat As String
Using con As New SqlConnection(ConStr),
cmd As New SqlCommand(SQL, con)
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = email
con.Open()
mat = cmd.ExecuteScalar().ToString()
End Using
Dim Dir As String = ConfigurationManager.AppSettings("path1").ToString
'Your original code was fine, no need for searchPattern.
'I added this so you could see if your search pattern was what you expected.
Dim searchPattern = mat.Substring(1) & "*.pdf"
Debug.Print(searchPattern) 'Appears in the Immediate window
Dim file = IO.Directory.GetFiles(Dir, searchPattern)
Return file
End Function

Error database is locked sqlite vb.net

hi I'm trying to insert a row to my database but I still get this error message (see below):
I used the methode using to be sure that the connection will be closed.
below the script for the insert button :
Private Sub MTB_Insert_Click(sender As Object, e As EventArgs) Handles MTB_Insert.Click
cmd = New SQLite.SQLiteCommand
Using con As New SQLite.SQLiteConnection(constr)
Try
'con.ConnectionString = constr
con.Open()
cmd.Connection = con
cmd.CommandText = "Insert Into Material_Type (Material_Type,Material_Type_Description) values(#Type,#Description)"
cmd.Parameters.AddWithValue("#Type", MTTB_Material_Type.Text)
cmd.Parameters.AddWithValue("#Description", MTTB_Material_Description.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Successful Added Data")
'Calling function load data
loadDatadg1()
'con.Dispose()
'con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
other parts of my code :
Public Class F_Update
Dim con As SQLite.SQLiteConnection
Dim cmd As SQLite.SQLiteCommand
Dim da As SQLite.SQLiteDataAdapter
Dim constr As String = "Data source =Database1.db"
Public Sub loadDatadg1()
Using con As New SQLite.SQLiteConnection(constr)
'con = New SQLite.SQLiteConnection(constr)
con.Open()
Dim str As String = "select * from Material_type"
da = New SQLite.SQLiteDataAdapter(str, con)
Dim ds As New DataSet
da.Fill(ds, "Tb.Material_Type")
dg1.DataSource = ds.Tables("Tb.Material_Type")
'da.Dispose()
'con.Close()
End Using
End Sub
Private Sub F_Update_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using con As New SQLite.SQLiteConnection(constr)
' con = New SQLite.SQLiteConnection(constr)
con.Open()
'MsgBox("OK")
'Calling the function Load form
loadDatadg1()
End Using
End Sub
another part :
Private Sub B_login_Click(sender As Object, e As EventArgs) Handles B_login.Click
Dim connectionString As String = "Data source =Database1.db"
Dim mSQL As String = "select User_Name,User_Password from User where (User_ID = 1 and User_Name = '" & T_User_Name.Text & "' and User_Password = '" & T_User_Password.Text & "')"
Dim dt As DataTable = Nothing
Dim ds As DataSet
Dim rd As SQLiteDataReader
Using con As New SQLiteConnection(connectionString)
Try
con.Open()
Dim cmd As New SQLiteCommand(mSQL, con)
cmd.ExecuteNonQuery()
rd = cmd.ExecuteReader
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
If rd.HasRows Then
F_Update.Show()
Me.Close()
Else
MessageBox.Show("Invalid User Name or Password")
End If
'con.Close()
End Using
End Sub
End Class
can some one help me please ? Thanks in advance

SqlBulkCopy doesn't copy all the rows from Excel sheet

I developed a Windows app to import Excel file and write the data into a SQL Server database table. The application works well but it starts writing from the line 27 or 30 and sometimes from line 29 of the Excel sheet. I need all the rows to be written to the database table from line 1 to line 4500.
My code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fdlg As OpenFileDialog = New OpenFileDialog
fdlg.Title = "Open File Dialog"
fdlg.InitialDirectory = "C:\"
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fdlg.FilterIndex = 2
fdlg.RestoreDirectory = True
If fdlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
ExcelFileName = fdlg.FileName
End If
'Excel 2007
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFileName + ";Extended Properties=""Excel 12.0 Xml;HDR=No;""")
Try
ExcelConnection.Open()
Catch ex As Exception
End Try
Dim expr As String = "SELECT * FROM [Sheet1$]"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
Dim objDR As OleDbDataReader
Dim SQLconn As New SqlConnection()
Dim ConnString As String = "Data Source=My_PC_Name;Initial Catalog=myDatabase;Integrated Security=True"
SQLconn.ConnectionString = ConnString
SQLconn.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLconn)
bulkCopy.DestinationTableName = "ItemDetails"
Try
objDR = objCmdSelect.ExecuteReader
If objDR.HasRows = True Then
bulkCopy.WriteToServer(objDR)
MessageBox.Show("You Successfuly import the excel file")
objDR.Close()
SQLconn.Close()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
End Sub
SQL is per definition not ordered. So to guarantee the order you will have to add a helper column (say column A) with your row_id. YOu can then use that later to select your data ordered.

Database Access in VB.NET

I have accessed a database in VB.NET using the following code:
Public Class Form1
Private Sub btnLoad_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnLoad.Click
Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = AddressBook.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM tblContacts"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Address Book")
MsgBox("Database Open")
con.Close()
MsgBox("Database Closed")
txtFirstName.Text = ds.Tables("AddressBook").Rows(0).Item(1)
txtSurname.Text = ds.Tables("AddressBook").Rows(0).Item(2)
End Sub
End Class
However in line "txtFirstName.Text = ds.Tables("AddressBook").Rows(0).Item(1)", it gives me an exception saying that an instance of an object should be created. I am not understanding what exactly the problem is. How can I create an instance, and of WHAT should I create an instance?
You used a space in
da.Fill(ds, "Address Book")
But no space in
txtFirstName.Text = ds.Tables("AddressBook").Rows(0).Item(1)
For the name of the table. Therefore a table with name "AddressBook" does not exist.

Resources