I am just learning to use Dapper for an SQL CE database.
I have typed the following code to open a connection:
Dim con As IDbConnection
con.ConnectionString = "Data Source=D:\test.sdf"
con.Open()
VS underlines the "con" in the line "con.ConnectionString = "Data Source=D:\test.sdf" and tells me:
Variable 'con' is used before it has been assigned a value. A null reference exception might occur.
To get rid of this comment, I have tried
Dim con As new IDbConnection
But that did not compile: 'New' cannot be used on an interface.
How do I deal with this?
Edit:
I have now tried the following:
Dim nStrongType As System.Data.Common.DbConnection()
Dim con As IDbConnection
con = nStrongType
That did not work. The compiler told me:
DBConnection cannot be converted to IDBConnection.
Thank you!
Related
I am using the built-in database for my program. When I try to put in the connection string, VB cannot detect the connection string and shows a syntax error on line 7 after the new SqlConnection. I am sure that I copied the complete connection string from the properties page.
I read this post but it seems to be a different question. Below is my code for the connection. Is there any mistake in my code? Thanks for all the help!
Imports System.Data.SqlClient
Public Class Login
Dim cmd As SqlCommand
Dim dr As SqlDataReader
Dim da As SqlDataAdapter
Dim sql As String
Dim conn As SqlConnection = New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\zhenwei\source\repos\Cafeteria Ordering System v1.0\Cafeteria Ordering System v1.0\Database1.mdf";Integrated Security=True")
That'll obviously show you a syntax error, look at your following line:
"C:\Users\zhenwei\source\repos\Cafeteria Ordering System v1.0\Cafeteria Ordering System v1.0\Database1.mdf"
Replace the double-quotes to ""<abc>"" to get like "<abc>" on execution because you've already used "<abc>" in New SqlConnection("...").
Rather than:
Dim conn As SqlConnection = New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\zhenwei\source\repos\Cafeteria Ordering System v1.0\Cafeteria Ordering System v1.0\Database1.mdf";Integrated Security=True")
you should have:
Dim conn As SqlConnection = New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=""C:\Users\zhenwei\source\repos\Cafeteria Ordering System v1.0\Cafeteria Ordering System v1.0\Database1.mdf"";Integrated Security=True")
I have the below code and it is returning an error:
Application defined or object defined error.
Public Sub TestConnection()
Dim conn
Set conn = New ADODB.connection
CONSTRING = "Provider=NZOLEDB;Data Source=location;Initial Catalog=database;User ID=username; Password=password;"
conn.Open CONSTRING
End Sub
Any idea why this is happening? I am not substituting the variables etc. just typing them directly into the string.
I think you need just to add a reference to Microsoft ActiveX Data Objects (ADO).
And for more information about using ADODB in Visual Basic.
As Microsoft examples, I suggest you to use this type of declaration:
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
I use QTP/UFT for my application testing.
I had to access my oracle DB (11g) to do some DB setup (to update records).
I use oracle.manageddataaccess.dll (referenced to myDBWrapper class library project).
I have below dlls
(myDBWrapper is the one I created - where the issue is present)
My connection string:
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=<HOST>)(PORT=<PORT>>)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=<SERVICENAME>)));User Id=<USERNAME>;Password=<PASSWORD>;
Issue:
The below code during conn.open() throws error. It works sometimes & sometimes throws an error that 'Object reference not to set an instance of an object' in the same machine.
conn = New OracleConnection()
conn.ConnectionString = ConnectionString
MsgBox("isnothing? : " & (conn Is Nothing).ToString) 'it is always False. So , not null
conn.Open() ' It throws an error that "Object reference not to set an instance of an object"
Dim cmd As OracleCommand = New OracleCommand(strQuery)
cmd.BindByName = True
cmd.Connection = conn
RowsAffected = cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Dispose()
Note:
It is not a resource leak. I just make 1 connection and dispose. No one else is connecting to the DB.
Issue happens - When QTP has COM lib. When i use that to automate & make it invisible (QTP.Visible = FALSE). If I use QTP.Visible = TRUE - issue does not happen. What kind of issue is this!!!
StackTrace :
Object reference not set to an instance of an object.
at OracleInternal.I18N.Conv.GetMaxBytesPerChar(Int32 charsetId)
at OracleInternal.ServiceObjects.OracleConnectionImpl.Connect(ConnectionString cs, Boolean bOpenEndUserSession)
at OracleInternal.ConnectionPool.PoolManager`3.CreateNewPR(Int32 reqCount, Boolean bForPoolPopulation, ConnectionString csWithDiffOrNewPwd)
at OracleInternal.ConnectionPool.PoolManager`3.Get(ConnectionString csWithDiffOrNewPwd)
at OracleInternal.ConnectionPool.OraclePoolManager.Get(ConnectionString csWithNewPassword)
at OracleInternal.ConnectionPool.OracleConnectionDispenser`3.Get(ConnectionString cs, PM conPM, ConnectionString pmCS, SecureString securedPassword, SecureString securedProxyPassword)
at Oracle.ManagedDataAccess.Client.OracleConnection.Open()
at myDBWrapper.Utility.DBUtil.OpenConnection()
Because that looks like VB.NET Have you got that code in a form load? That event is unpredictable if you are not showing the form.
have u tried the oracle connection using the ADOB connection object ? you need to have the Oracle driver installed and it will help you to connect to the DB by creation the ADOB connection object
Try this
conn = New Oracle.ManagedDataAccess.Client.OracleConnection(ConnectionString)
NET and using MS Access as database. I'm trying to get data from SQL and place it in a variable and print it in a Message box to confirm that the variable holds the data. But when I run my code it gives me an error message and highlights
Dim conn As New OleDbConnection and conn.Open()
"An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: The ConnectionString property has not been initialized."
It does not run the sql query. Please help me figure this out. Merci.
Imports System.Data.OleDb
Public Class ModifyForm
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
Dim conn As New OleDbConnection
Private Sub eNumText_SelectedIndexChanged(sender As Object, e As EventArgs) Handles eNumText.SelectedIndexChanged
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
Dim conn As New OleDbConnection(connstring)
conn.Open()
Dim DBID As String ' Or whatever type you're using for the ID field
Dim DBFirstName As String
Dim SqlQuerry As String = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
Dim SqlCommand As New OleDbCommand
Dim SqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
With SqlCommand
.CommandText = SqlQuerry
.Connection = conn
End With
With SqlAdapter
.SelectCommand = SqlCommand
.Fill(Table)
End With
For i = 0 To Table.Rows.Count - 1
DBID = Table.Rows(i)("EmpID")
DBFirstName = Table.Rows(i)("FirstName")
MsgBox(DBID)
MsgBox(DBFirstName)
Next
conn.Close()
End Sub
End Class
You need to actually use your connection string.
But first let's remove the duplicate declaration of your connection. Remove Dim conn As New OleDbConnection from the very top of your code (the one outside of the method) it's not needed since you are declaring again inside of the method. Then, inside the method update your connection initialization to:
Dim conn As New OleDbConnection(connstring)
More than that, you need to initialize your command, passing it the connection string and query string. The Adapter needs to have a reference to the command and you need to call
SQLAdapter.fill(Table)
To get your data in the table.
Please look up how to use these objects... Simply creating new instances of them doesn't implicitly assign all of the configuration information that each object needs.
One note is to make sure that you dispose your objects that implement the IDisposable interface to free the unmanaged resources. It is not enough to simply close your connection--this will lead to memory leaks, not just with SQL objects but anything that uses resources not directly managed by. .NET
SQLCommand.dispose()
SQLAdapter.dispose()
Table.dispose()
conn.dispose()
conn.close()
And finally, once you get it working using the information provided above and some googling, you then need to address SQLInjection. Right now your query string is prone to injection whereas a user could potentially type some malicious text into the text box you refer to in your query string and manipulate your database without your permission. To get around this, look into parameterized commands.
I'm posting from my phone or else I'd provide a full working set of code; but at the same time I don't want to rewrite the whole thing for you. There should be enough info in this answer to help you do a little research.
This MSDN page contains info on the OleDb data adapter as well as a short example at the end. It also includes links and references for the rest of the OleDb classes and to some tutorials:
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter.aspx
This MSDN page contains info on the SQLDataAdapter and includes a short example at the very bottom. Although a different class, the usage is fundamentally the same as the OleDb classes: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx
Though not in vb (its in c#) the usage is the same, just slightly different syntax (best I could find from my phone at the moment). Again this is for the SQLDataAdapter class, but usage is fundamentally the same: http://www.codeproject.com/Tips/462730/Five-different-overloads-of-the-DataAdapter-Fill-m
I am having some trouble in some Visual Basic code where although I have declared a variable, when I try to give it a value, Visual Studio returns an error saying that the variable hasn't been declared. Here is the block of code:
Private Sub chkbox_ta_CheckedChanged(sender As Object, e As EventArgs) Handles chkbox_ta.CheckedChanged
Dim query As String = "SELECT * FROM [Hiragana List] WHERE Pronunciation='Ta';"
Dim instruction As SqlCommand (query, connection)
Dim da As New SqlDataAdapter
da.SelectCommand = instruction
da.Fill(HiraganaList)
End Sub
The error is thrown up by the 'instruction' variable and Visual Studio hasn't provided any solutions. In addition to this, the query argument within the instruction variable returns the error 'Array bounds cannot appear in type specifiers'. I am still getting used to working with SQL in VB and any explanation which would teach me how to avoid these errors would be very helpful.
Wrong syntax in declaration and initialization of the SqlCommand.
The right syntax is one of the following:
Dim instruction As SqlCommand = new SqlCommand(query, connection)
or
Dim instruction As New SqlCommand (query, connection)
or just
Dim instruction = new SqlCommand(query, connection)
The Dim Statement has numerous variations the should be studied carefully (especially in the early days with the language)
Data types (string, integer, date) do not need a "new" declaration.
But when you define something that is a class (Like SqlCommand or one you create yourself) it will need to be initialized with "new".
Syntax examples from Steve's earlier post
Dim instruction As SqlCommand = new SqlCommand(query, connection)
Dim instruction As New SqlCommand (query, connection)
Dim instruction = new SqlCommand(query, connection)
Some links that might help out:
http://msdn.microsoft.com/en-us/library/47zceaw7.aspx
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand%28v=vs.110%29.aspx