creating a ConnectionString in vb.net - vb.net

i want to create a connection to my database in my application on vb.net
i stored a procedure called "CTable" that will create tables if they don't exist
im using this code:
Dim strConnection As String
strConnection = "Data Source=Localhost; Initial Calalog=Northwind; Integrated Security=True"
Dim MyConn As SqlConnection
Dim cmd As SqlCommand
MyConn = New SqlConnection(strConnection)
Dim query As String = "EXEC CTable"
cmd = New SqlCommand(query, MyConn)
MyConn.Open()
cmd.ExecuteNonQuery()
MyConn.Close()
but he is giving this error:
" An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll
Additional information: Keyword not supported: 'initial calalog'"
my question is : what should i put in my 'strConnection' variable to be able to execute my CTable Procedure????

You have a typo in the connection string. Try "Catalog" instead of "Calalog" ;)

The word is Catalog not Calalog.
So this should work:
strConnection = "Data Source=Localhost; Initial Catalog=Northwind; Integrated Security=True"
Note that you also have to set the CommandType to CommandType.StoredProcedure.
But always use the Using statement to ensure that unmanaged resources are disposed even on error:
Dim strConnection = "Data Source=Localhost; Initial Catalog=Northwind; Integrated Security=True"
Using MyConn = New sqlclient.SqlConnection()
Using cmd = New SqlClient.SqlCommand("EXEC CTable")
cmd.CommandType = CommandType.StoredProcedure
MyConn.Open()
cmd.ExecuteNonQuery()
End Using
End Using ' also closes the conection

Standard Security
Data Source=serverName\instanceName;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Trusted Connection
Data Source=serverName\instanceName;Initial Catalog=myDataBase;Integrated Security=SSPI;

Related

VB.NET - Key word is not supported: provider

When I try to connect to AcessDB, I get the error
"Keyword is not supported: provider".
When I try to change provider, I get another error. When I delete provider tag, I also get an error.
Dim Exists As Boolean = False
Dim ConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Name\Documents\Visual Studio 2010\Projects\datagrid\datagrid\pokus.accdb;Persist Security Info=False;"
Dim connection As New SqlConnection(ConnectionString)
Try
connection.Open()
Dim command As SqlCommand = connection.CreateCommand
command.CommandText = "SELECT * FROM studenti"
Dim reader As SqlDataReader = command.ExecuteReader
If reader.HasRows Then
Exists = True
Else
Exists = False
End If
reader.Close()
command.Dispose()
Catch ex As Exception
Console.Write(ex.Message)
Finally
connection.Close()
End Try
SqlConnection, SqlCommand, etc. are SQL Server-specific classes. You can't use them to connect to MS Access.
The documentation for SqlConnection makes this very clear:
Represents an open connection to a SQL Server database.
Consider using the OldDbConnection and related classes instead.
I always write wrapper classes for database connections, and I always recommend the same.
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Name\Documents\Visual Studio 2010\Projects\datagrid\datagrid\pokus.accdb;Persist Security Info=False;"
Dim Conn As New OleDbConnection
Conn.ConnectionString = sConnectionString
Conn.Open()
Dim sQuery As String = "SELECT * FROM studenti"
Dim da As New OleDbDataAdapter(sQuery, Conn)
Dim dt As New DataTable
da.Fill(dt)
Conn.Close()

vb.net sql parameterization

I really need help this time. I search everywhere, tried numerous solutions. but i can't seem to solve my problem. Now i'm going to ask, please help. I have been having this problem for a week now.
ExecuteSQL("select * from account_database where idnum= #idnum and password= #pass")
'Dim idnum As New SqlParameter("#idnum", SqlDbType.VarChar)
'Dim pass As New SqlParameter("#pass", SqlDbType.VarChar, -1)
'idnum.Value = idnumtxt.Text
'pass.Value = output
'cmd.Parameters.Add(idnum)
'cmd.Parameters.Add(pass)
cmd.Parameters.Add("#idnum", SqlDbType.VarChar).Value = idnumtxt.Text
cmd.Parameters.Add("#pass", SqlDbType.VarChar, -1, "password").Value = output
those commented out lines are the codes which i have tried, also there are codes which i implemented that also failed.
The error message concludes as "Must declare scalar variable #idnum"
i really need help please. Please shine some light.
This is the code what the function executeSQL contains :
Public Shared Sub ExecuteSQL(ByVal strSQL As String)
Try
If connection.State = 1 Then ' check connection if open
connection.Close()
End If
' connection
connection.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
connection.Open()
Dim rowAffected As Integer = 0
'cmd = New SqlCommand(strSQL, connection) 'buiding the sql command with the use of strSQL (sql statement) and connection (database connection)
cmd = New SqlCommand(strSQL, connection)
DARec = New SqlDataAdapter(strSQL, connection) 'buiding the adapter
cb = New SqlCommandBuilder(DARec)
rowAffected = cmd.ExecuteNonQuery() 'executing of sql statement
successID = 1
connection.Close()
Catch ex As Exception
successID = 0
MsgBox(ex.Message)
End Try
End Sub
Thanks and please help.
Problem is simply you're doing this in the wrong order. You're attempting to execute your SQL statement before defining the parameters. You don't need ExecuteSQL() until you've defined your parameters. It likely breaks on the following line in ExecuteSQL()
' See how many rows the query will impact
' Since #idnum and #pass are not defined until the
' ExecuteSQL() sub is finished, this line breaks.
rowAffected = cmd.ExecuteNonQuery()
You need to build your SqlCommand() to first include the select statement, and then use AddWithValue() on the parameters you've defined in the string. Defining the datatypes is also unnecessary because your database already knows, and form validation should handle input.
' Define your connection
connection.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
' Setup your SQL Command.
cmd = New SqlCommand("select * from account_database where idnum = #idnum and password = #pass", connection)
' Define the parameters you've created
cmd.Parameters.AddWithValue("#idnum", idnumtxt.Text)
cmd.Parameters.AddWithValue("#pass", output)
' Now execute your statement
connection.open()
cmd.ExecuteNonQuery()
connection.close()
And here is a better version of the above code, since you understand the order of events now. This ensures that in the event of exception the connection is closed.
strConn = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
strSQL = "select * from account_database where idnum = #idnum and password = #pass"
Using connection As New SqlConnection(strConn), cmd As SqlCommand(strSQL, connection)
cmd.Parameters.Add("#idnum", SqlDbType.VarChar).Value = idnumtxt.Text
cmd.Parameters.Add("#pass", SqlDbType.VarChar, -1, "password").Value = output
connection.Open()
cmd.ExecuteNonQuery()
End Using
Try this:
cmd.Parameters.AddWithValue("idnum", idnumtxt.Text)
Reference:
SqlParameterCollection.AddWithValue # MSDN.
It should just be a case of the following to add an input param
cmd.Parameters.Add("#idnum", idnumtxt.Text)
Except you'll need cmd.parameters.add() before the executesql as you're currently defining your params after executesql has ran.

select data from Dataset Vb.Net

ok first ill explain what ive done.
First I imported an access db into my vb app it then named the dataset etc.
this is how my dataSet looks:
1 table
4 columns
so Far i have this:
Dim ds As ElementsDataSet
Dim dt As ElementsDataSet.ElementsDataTable
Dim conn As SqlConnection = New SqlConnection("Data Source=|DataDirectory|\Elements.accdb")
Dim selectString As String = "Select Atomic Mass FROM Elements WHERE No =" & mol
Dim cmd As New SqlCommand(selectString, conn)
If conn.State = ConnectionState.Closed Then conn.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
While datareader.Read = True
MessageBox.Show(datareader.Item("Atomic Mass"))
End While
datareader.Close()
and upon executing this I get this error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
The problem is you are using a SQLConnection to open a Access database. This wont work.
You either need a SQLServer database or to use the OleDbConnection for a Access database.
Here is a Microsoft KB article to help you connect to the Access database:
How To Retrieve and Display Records from an Access Database by Using ASP.NET, ADO.NET, and Visual Basic .NET and this one over at CodeProject: http://www.codeproject.com/Articles/8477/Using-ADO-NET-for-beginners
Private Sub ReadRecords()
Dim conn As OleDbConnection = Nothing
Dim reader As OleDbDataReader = Nothing
Try
conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Temp\Elements.accdb"))
conn.Open()
Dim cmd As New OleDbCommand("Select Atomic Mass FROM Elements WHERE No =" & mol, conn)
reader = cmd.ExecuteReader()
While reader.Read = True
MessageBox.Show(reader.Item("Atomic Mass"))
End While
Finally
If reader <> Nothing Then
reader.Close()
End If
If conn <> Nothing Then
conn.Close()
End If
End Try
End Sub

vb.net Oracle connection using TNS Name?

I have put my tns connection into the .ora file and am now able to conenct to it using SQL plus and can ping it :tnsping myConn.
I've also added the connection to the ODBC Manager and connecting successfully when tetsing conneciton through the ODBC tool.
now i'm having an issue making a connection to it using vb.net
i've tried the following:
oODBCConnection = New Odbc.OdbcConnection(connStr)
oODBCConnection.Open()
where my connStr is:
Data Source=tns.dev;User Id=MyUser;Password=MyPass;
per: http://www.connectionstrings.com/oracle and http://www.shabdar.org/c-sharp/101-connect-to-oracle-using-asp-net-and-csharp.html
what am i doing wrong? it's telling me i need to specify a driver, how do i do it?
Thank you!
the error i'm getting is:
ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
Did you checked the tnsnames.ora file? Is there any entry for tns.dev?
http://www.mike-devlin.com/oracle/tnsnames_ora.htm
That is not an oracle error - it sounds like you did not create a system dsn. This code looks like it expects a DSN by name of tns.dev.
That said, I would not use odbc if I could help it. You might want to look at Oracle Data Provider for .net
http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
ODBCConnection was incorrect.
solution:
Dim myConnection As OleDbConnection
Dim myCommand As OleDbCommand
Dim myConnection As New OracleConnection(connStr)
myConnection.Open()
I´ve been using the following code in Vb.net
Dim conn As New Odbc.OdbcConnection
Dim cmd As New Odbc.OdbcCommand
Dim drResult As Odbc.OdbcDataReader
Dim connString As String
Dim QuerySQL As String
connString = "Driver={Microsoft ODBC for Oracle};CONNECTSTRING=(DESCRIPTION=(ADDRESS= (PROTOCOL=TCP)(HOST=ORACLEDB01)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORACLE_INSTANCE_NAME)));Uid=john;Pwd=mypassword;"
QuerySQL = "select first_name, last_name from employees where id = 28"
conn.ConnectionString = connString
conn.Open()
cmd.Connection = conn
cmd.CommandText = QuerySQL
drResult = cmd.ExecuteReader()
While drResult.Read
TextBox1.Text = TextBox1.Text & drResult("last_name") & ", " & drResult("first_name") & Environment.Newline
End While
drResult.Close()

What is wrong on connection string

I am trying to connect database.sdf on same director. Using following code but gives me connection error. What I am doing wrong. Please help me.
Dim connstring As String
Dim con As SqlCeConnection
Dim command As SqlCeCommand
connstring = "Persist Security Info = False; Data Source = '.\database.sdf', Password = 'pswrd', File Mode = 'shared read'"
con = New SqlCeConnection
con.Open()
command = New SqlCeCommand("select * from users where Name=? and Password=?", con)
I think you're missing some code... or maybe that's the problem, you never bind your SqlCeConnection to connstring
Dim con As SqlCeConnection
Dim command As SqlCeCommand
con = New SqlCeConnection("Persist Security Info=False;Data Source=.\database.sdf;Password=pswrd;File Mode=shared read")
con.Open()
command = New SqlCeCommand("select * from users where Name=? and Password=?", con)
You do not need the single quotes (') in the different parts of the connection string, and you should be using a semi-colon (;) to separate the different values.
"Persist Security Info = False; Data Source = .\database.sdf; Password = pswrd; File Mode = shared read;"
Apart from that, you do not appear to be using the connection string in your code. You should be using it to open the connection:
con = New SqlCeConnection(connstring)
Check out Connection Strings for great connection string assitance.
It looks like your line:
connstring = "Persist Security Info = False; Data Source = '.\database.sdf', Password = 'pswrd', File Mode = 'shared read'"
is using both "," and ";" to separate the parameters. Update then all to use ";"