i used this function to create a database:
Public Function CreateAccessDatabase (ByVal DatabaseFullPath As String) As Boolean
Dim bAns As Boolean
Dim cat As New ADOX.Catalog()
Try
Dim sCreateString As String
sCreateString = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
DatabaseFullPath
cat.Create(sCreateString)
bAns = True
Catch Excep As System.Runtime.InteropServices.COMException
bAns = False
Finally
cat = Nothing
End Try
Return bAns
End Function
and i want to connect it through code, i tried this but it doesnt work:
Try
Dim constring As String
constring = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Utilizador.Utilizador-PC\Documents\Visual Studio 2013\Projects\WindowsApplication1\WindowsApplication1\Doc_Vendas_Cab.mdf;"
Dim conn As New SqlConnection(constring)
conn.Open()
MsgBox("Connected")
conn.Close()
Catch Ex As Exception
MsgBox(Ex)
End Try
how should i do it?
You are using ms-access database in you code why are you using SqlConnection provider it is for SQL server database.
You have to use OleDb.OleDbConnection provider.
See, this example link is helpful
Try
Dim constring As String
constring = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Utilizador.Utilizador-PC\Documents\Visual Studio 2013\Projects\WindowsApplication1\WindowsApplication1\Doc_Vendas_Cab.mdf;"
Dim conn As New OleDb.OleDbConnection(constring)
conn.Open()
MsgBox("Connected")
conn.Close()
Catch Ex As Exception
MsgBox(Ex)
End Try
Related
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
I'm trying to retrieve binary data from a database.
I got this error: "Error: Fill: selectcommand.connection property has not been". I can't locate the error.
Public Shared Function BinaryData(ByVal sFileName As String) As Byte()
Dim strSql As String
Dim binaryFile As Byte() = Nothing
Dim dt As DataTable
Dim myCommand As New SqlCommand
Dim sqlConn As New SqlConnection
sqlConn = New SqlConnection("Data Source=xxx;Initial Catalog=xx;Persist Security Info=True;User ID=wxx;Password=xx;MultipleActiveResultSets=True;Application Name=EntityFramework")
sqlConn.Open()
myCommand.Connection = sqlConn
strSql = "SELECT Data FROM tbldrive WHERE Filename = '" + sFileName + "'"
Dim scmd As New SqlCommand(strSql, sqlConn)
dt = DataComponent.DataTableQuery(DataComponent.SqlConn, strSql)
If dt.Rows.Count > 0 Then
Try
binaryFile = DirectCast(dt.Rows(0).Item("Data"), Byte())
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Return binaryFile
End Function
It looks like you've tried a few things in that code but accidentally left the remains of some attempts in there.
There are some things you could do a bit differently: as you're only after one item from the database, you can use ExecuteScalar; and when the code has finished with the SQL connection and command, they should have .Dispose() called on them - the Using statement will take care of that for you even if something goes wrong. Finally, you should always use SQL parameters to pass parameters to an SQL query - it makes it more secure and avoids having to worry about things like apostrophes in the value.
Public Shared Function BinaryData(ByVal sFileName As String) As Byte()
Dim sql As String = "SELECT Data FROM tbldrive WHERE Filename = #fname"
Dim connStr = "Data Source=xxx;Initial Catalog=xx;Persist Security Info=True;User ID=wxx;Password=xx;MultipleActiveResultSets=True;Application Name=EntityFramework"
Dim binaryFile As Byte() = Nothing
Using conn As New SqlConnection(connStr),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {
.ParameterName = "#fname",
.SqlDbType = SqlDbType.NVarChar,
.Size = 255,
.Value = sFileName})
conn.Open()
Dim obj As Object = cmd.ExecuteScalar()
If obj IsNot Nothing Then
Try
binaryFile = DirectCast(obj, Byte())
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Using
Return binaryFile
End Function
(You may need to adjust the .SqlDbType and .Size parameters: they need to match the column type and size in the database. Also, you probably don't need MultipleActiveResultSets.)
The problem seems to be that you have two SqlCommand objects:
Dim myCommand As New SqlCommand
...
myCommand.Connection = sqlConn
It's assigned but not used.
Then you have defined another one:
Dim scmd As New SqlCommand(strSql, sqlConn)
that is not used either.
And I don't know why you have this:
dt = DataComponent.DataTableQuery(DataComponent.SqlConn, strSql)
Do you even need a SqlCommand if you are not using it ?
Clean up your code by removing unused variables.
Protected Sub login_btn_Click(sender As Object, e As EventArgs) Handles login_btn.Click
Dim connString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
connString = "Data Source=.\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True"
sql = "select NET_ID, Password from User"
connection = New SqlConnection(connString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
Dim sqlReader As SqlDataReader = command.ExecuteReader()
While sqlReader.Read()
If (Password.Text = sqlReader("Password") And NET_ID.Text = sqlReader("NET_ID")) Then
Response.Redirect("Creation.aspx")
End If
End While
sqlReader.Close()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
I always get the msg box saying that connection can noy be established.
I tried to open SQL Server Management Studio at the same time the code running but I didn't anything.
From your exception text:
Incorrect syntax near the keyword 'User'
User is reserved keyword in SQL Server.
Basically not recommended to create table having name equals to reserved keywords, but if you really need this name, you have to surround it with square brackets in your query like this:
select NET_ID, Password from [User]
I from what I can see your connection string looks like it's creating the error you forget to escape the "\" character.
additional you can move code inside try block so that you get specific error code
so to escape you can change the line to become
connString = #"Data Source=.\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True";
OR
connString = "Data Source=.\\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True";
so update your code to become:
Protected Sub login_btn_Click(sender As Object, e As EventArgs) Handles login_btn.Click
Dim connString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
Try
connString = #"Data Source=.\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True"
//OR USE BELOW
//connString = "Data Source=.\\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True"
sql = "select NET_ID, Password from User"
connection = New SqlConnection(connString)
connection.Open()
command = New SqlCommand(sql, connection)
Dim sqlReader As SqlDataReader = command.ExecuteReader()
While sqlReader.Read()
If (Password.Text = sqlReader("Password") And NET_ID.Text = sqlReader("NET_ID")) Then
Response.Redirect("Creation.aspx")
End If
End While
sqlReader.Close()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
Protected Sub login_btn_Click(sender As Object, e As EventArgs) Handles login_btn.Click
Dim connString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
connString = "Data Source=.\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True"
//Instead of
sql = "select NET_ID, Password from User"
//I used this
sql = "SELECT [NET_ID], [Password] FROM [User] "
And it worked
connection = New SqlConnection(connString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
Dim sqlReader As SqlDataReader = command.ExecuteReader()
While sqlReader.Read()
If (Password.Text = sqlReader("Password") And NET_ID.Text = sqlReader("NET_ID")) Then
Response.Redirect("~/Request/Creation.aspx")
End If
End While
sqlReader.Close()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
thanks everyone
i try this simple code with oledb connection but connection not open
Imports System.Data.OleDb
Public Class WebForm2
Inherits System.Web.UI.Page
Protected Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click
Dim connetionString As String
Dim cnn As OleDbConnection
connetionString = "Provider=SQLOLEDB;Data Source=((localdb)\v11.0);Initial Catalog=test;User Id=MyUsername; Password=MyPassword;Integrated Security=SSPI;"
cnn = New OleDbConnection(connetionString)
Try
cnn.Open()
MsgBox("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
i also try this connection string
connetionString = "Provider=SQLOLEDB;Data Source=test;Integrated Security=SSPI;"
same DB working well with sql client this connection string
Imports System.Data.SqlClient
Public Class WebForm2
Inherits System.Web.UI.Page
Dim globalp As String
Dim globals As String
Private strConn As String = "Data Source=(localdb)\v11.0;Initial Catalog=test;Integrated Security=True"
extra code not mention for simplicity of question.
any thing extra required so please mention in comments.
also another problem is that some told me that this issue arise due to SQL Server Authentication
i try to change security authentication mode in visual studio built in sql server but i don't get properties popup menu or right below in vs corner section of properties, from Object Explorer,
New error occur in this code section `Imports System.Data.OleDb
Public Class WebForm2
Inherits System.Web.UI.Page
Dim globalp As String
Dim globals As String
'Dim strConn As String = "Provider=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=((localdb)\v11.0);Initial Catalog=test;Integrated Security=SSPI;"
Dim strConn As String = "Provider=SQLNCLI11.1;Integrated Security=SSPI;Initial Catalog=Test;Data Source=(localdb)\v11.0;"
Dim conn As OleDbConnection
' Dim strConn As String = "Provider=SQLOLEDB; Data Source=(localdb)\v11.0; Initial Catalog=test; Integrated Security=SSPI"
' Private strConn As String = " Provider=Microsoft.Jet.OLEDB.4.0; Data Source=(localdb)\v11.0;Initial Catalog=test; User Id=MyUsername; Password=MyPassword"
' Private sqlCon As OleDbCommand
'Private strConn As OleDbCommand
'Provider=SQLOLEDB;
Protected Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click
If Page.IsValid Then
' cnn = New OleDbConnection(strConn)
' cnn.Open()
' MsgBox("Connection Open ! ")
' cnn.Close()
'sqlComm.CommandText = "sp1_userinformation"
' sqlComm.CommandType = CommandType.StoredProcedure
' sqlComm.Parameters.AddWithValue("UserName", name.Text)
' sqlComm.Parameters.AddWithValue("pass_word", fname.Text)
' sqlComm.Parameters.AddWithValue("CNIC", (cnic.Text))
' sqlComm.Parameters.AddWithValue("PartialAddress", (limitedtextarea.Text))
' sqlComm.Parameters.AddWithValue("Email", (email.Text))
' sqlCon.Open()
'lcit.Text = sname
' sqlComm.ExecuteNonQuery()
' Dim sname As String = name.Text
Dim sfname As String = fname.Text
Dim scnic As String = cnic.Text
Dim slimit As String = limitedtextarea.Text
Dim semail As String = email.Text
Dim stel As Int64 = Int64.Parse(tel.Text)
Dim stel1 As Int64 = 0 & stel
Dim query As String = String.Empty
Dim sdob As Date = Date.Parse(dob.Text)
query &= "INSERT INTO Userinfo (UserName, pass_word, CNIC, "
query &= " PartialAddress, Email, Telephone,DateOfBirth) "
query &= "VALUES (#colName,#colID, #colPhone, #colBranch,#colCourse,#coldblFee,#dobv)"
' query &= " PartialAddress, Email) "
' query &= "VALUES (#colName,#colID, #colPhone, #colBranch,#colCourse)"
' Using (sqlCon)
'sqlCon = New SqlConnection(strConn)
' Dim sqlComm As New SqlCommand()
' sqlComm.Connection = sqlCon
Using conn As New OleDbConnection(strConn)
Using comm As New OleDbCommand()
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("#colName", username.Text)
.Parameters.AddWithValue("#colID", sfname)
.Parameters.AddWithValue("#colPhone", scnic)
.Parameters.AddWithValue("#colBranch", slimit)
.Parameters.AddWithValue("#colCourse", semail)
.Parameters.AddWithValue("#coldblFee", stel1)
.Parameters.AddWithValue("#dobv", sdob)
End With
' Try
conn.Open()
comm.ExecuteNonQuery()
' Catch(ex as SqlException)
'MessageBox.Show(ex.Message.ToString(), "Error Message")
' End Try
End Using
End Using
' End Using
End If
End Sub`
Error is (Must declare the scalar variable "#colName".)
error location comm.ExecuteNonQuery()
Try with SQL Server Native Client instead:
Provider=SQLNCLI11.1;Integrated Security=SSPI;Initial Catalog=Test;Data Source=(localdb)\v11.0;
EDIT:
Your code would be:
Dim connetionString As String
Dim cnn As OleDbConnection
connetionString = "Provider=SQLNCLI11.1;Integrated Security=SSPI;Initial Catalog=Test;Data Source=(localdb)\v11.0;"
cnn = New OleDbConnection(connetionString)
Try
cnn.Open()
MsgBox("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
Side Note: sql localdb does not work with SQL Server standard authentication, it only works with Windows integrated authentication.
OleDbCommand's use positional parameters and the question mark ? as the parameter marker, as oposed to SqlCommand's that use named parameters. So the sql statement should be:
INSERT INTO Userinfo
(
UserName, pass_word, CNIC, PartialAddress,
Email, Telephone, DateOfBirth
)
VALUES (?,?, ?, ?,?,?,?)
To add parameters to OleDbCommand.Parameters collection you don't need to change anything, you can use the parameter name you want as long as all parameter names are different. But rememeber, you need to add the parameters in order, because parameters are positional.
Every time I tried to connect to the database it give me this error "The ConnectionString property has not been initialized"
what can I do to solve this?
here are my codes
Module Module1
Function GetInfoForStudent(ByRef QueryName As String, ByVal UserName As String, ByVal Password As String) As DataTable
Using Con As New SqlConnection
Try
Using OleCon As New SqlConnection
Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library
Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Con.Open()
Dim Cmd As SqlCommand = Con.CreateCommand()
Cmd.CommandType = CommandType.StoredProcedure
Cmd.CommandText = QueryName
Cmd.Parameters.AddWithValue("#user", UserName)
Cmd.Parameters.AddWithValue("#pass", Password)
Dim da As New SqlDataAdapter(Cmd)
Dim ds As New DataTable()
da.Fill(ds)
Return ds
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Using
End Function
End Module
Sub ShowStudentInfo()
Dim dt As DataTable = GetInfoForStudent("MyStoredProcName", "#user", "#pass")
' Since (presumably) only one is returned
With dt.Rows(0)
' Assign your text boxes
StudentIDTextBox.Text = .Item("StudentID")
LoginIDTextBox.Text = .Item("LoginID")
Student_NameTextBox.Text = .Item("Student Name")
Student_addressTextBox.Text = .Item("Student address")
End With
End Sub
You never assigned your connection string to the connection object, just like the error is saying.
Insert a line setting the connection string before con.open.
Con.connectionstring = connection
Con.Open()
Or better yet, change your using statement as follows
Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Using Con As New SqlConnection(connection)
You are creating the connection string object but never assigning it to your SqlCommand object.