Error in oledb database connectivity - sql-server

Connection
Conn_String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\UTS.mdb"
conn = New OleDbConnection(Conn_String)
conn.Open()
Query
sqlCmd.Connection = conn
sqlCmd.CommandText = "INSERT into Customer_Master Values (#Cust_ID,#Cust_Name,#Cust_Address,#Cust_ContactNo)"
sqlCmd.Parameters.AddWithValue("#Cust_ID", SqlDbType.Int).Value = Cust_id
sqlCmd.Parameters.AddWithValue("#Cust_Name", SqlDbType.Text).Value = txtcname.Text
sqlCmd.Parameters.AddWithValue("#Cust_Address", SqlDbType.Text).Value = txtcadd.Text
sqlCmd.Parameters.AddWithValue("#Cust_ContactNo", SqlDbType.Int).Value =
txtccontact.Text.ToString
sqlCmd.ExecuteNonQuery()
conn.Close()
Problem
When I Click the button containing the above code it gives me following error..
An unhandled exception of type System.NullReferenceException occurred in UTS.exe
Additional information: Object reference not set to an instance of an object.
The error is n this line-->sqlCmd.Connection = conn

When I searched in ExcuteNonQuery to check myself, I found this example first:
msdn
it shows an example of intialising a command object:
SqlCommand command = new SqlCommand(queryString, connection);

Related

Getting data from a stored procedure

I have a stored procedure like this:
Select name, surname from student
and I can't get data with VB.Net.
My code is:
Dim reader As SqlDataReader
With dbCmd
.CommandType = CommandType.StoredProcedure
.CommandText = "sp_myPersonalSP"
End With
reader = dbCmd.ExecuteReader()
But Visual Studio send me an exception when it try "reader = dbCmd.ExecuteReader()":
Procedure sp_myPersonalSP has no parameters and arguments were supplied.
Thanks! I am a newbie in VB.Net :-(
A function that returns a datatable from Sql Server executing a stored procedure:
Public Function GetApplicationType() As DataTable
Dim MyDataTable As DataTable = New DataTable()
' The connection string information is in the web.config file - see below
Dim con = ConfigurationManager.ConnectionStrings("MyConnectionString").ToString()
Dim MyDataAdapter As SqlDataAdapter = New SqlDataAdapter("GetSomeData", con)
MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
' add the parameters in the same order and type as what the stored procedure expects, they must match the names in the stored procedure and are case sensitive.
MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("#ParameterName", SqlDbType.VarChar, 10));
MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("#Parametername2", SqlDbType.VarChar, 40));
MyDataAdapter.SelectCommand.Parameters["#ParameterName"].Value = somedata1;
MyDataAdapter.SelectCommand.Parameters["#ParameterName2"].Value = somedata2;
MyDataAdapter.Fill(MyDataTable)
Return MyDataTable
End Function
web.config
<connectionStrings>
<add name="MyConnectionString" connectionString="server=192.168.11.11;database=Test;uid=someusername; pwd=somepassword" providerName="System.Data.SqlClient" />
</connectionStrings>
You can display your query results in a DataGridView. You need to have a connection for the command to execute. Open the connection before you execute the command. The Using...End Using statements with ensure that your objects are closed and disposed event if there is an error.
Private Sub GetData()
Using cn As New SqlConnection("Your Connection String")
Using dbCmd As New SqlCommand
With dbCmd
.CommandType = CommandType.StoredProcedure
.CommandText = "sp_myPersonalSP"
.Connection = cn
End With
cn.Open()
Using reader As SqlDataReader = dbCmd.ExecuteReader()
'You can view the result of your query in a DataGridView
Dim dt As New DataTable
dt.Load(reader)
DataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub
to retrieve data from stored procedure, just call your stored procedure name like this.
Dim stringquery = "CALL YOURSTOREDPROCNAME()"
Try my Code:
Dim dt as new Datatable
con.Open()
Dim query = "Call StoredProcedureName()"
command = New SqlCommand(query, con)
adapter.SelectCommand = command
dt.Clear()
adapter.Fill(dt)
con.Close()
-KEVIN

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

I've been trying to view a table in a datagridview by using a the table name chosen in combobox but I still get the error
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
I don't know what is wrong.
This is my code
Dim myconnection As New SqlConnection("data source=.\sqlexpress; initial catalog=itses;integrated security=true")
Dim da As New SqlDataAdapter
Dim source1 As New BindingSource
Dim table As New DataTable
Dim ds As New DataSet
myconnection.Open()
Dim query As String
query = "Select * from '" & ComboBox6.SelectedItem & "'"
mycommand = New SqlCommand(query, myconnection)
da.SelectCommand = mycommand
da.Fill(table)
source1.DataSource = table
DataGridView2.DataSource = source1
da.Update(table)
myconnection.Close()
Most likely, it's just the unneeded single quotes around the table name you're using - try this instead:
Dim query As String
query = "Select * from " & ComboBox6.SelectedItem
The query should be
Select * from TableName
(without any single quotes or anything else around the table name)
have you tried adding ToString() and removing '' like so
query = "Select * from "& ComboBox6.SelectedItem.ToString() &""
or just the SelectedItem should work
query = "Select * from "& ComboBox6.SelectedItem &""

ExecuteNonQuery: Connection property has not been initialized. even with connection open

I am trying to update a sql db in an "IF THEN" statement but I am getting :
ExecuteNonQuery: Connection property has not been initialized.
When I run my code.
Private m_cn As New SqlConnection
If oldcost <> newcost Then
'Dim myconnect As New SqlClient.SqlConnection
m_cn.ConnectionString = "Data Source=localhost;Initial Catalog=tires;Integrated Security=True"
m_cn.Open()
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
'm_cn.Open()
mycommand.CommandText = "INSERT INTO tire_price_changes (change_date, old_cost, old_retail,new_cost,new_retail,tire_id) VALUES (#change_date, #Nold_cost, #old_retail, #new_cost, #new_retail, #tire_id)"
Try
mycommand.Parameters.Add("#change_date", SqlDbType.Date).Value = tiredate
mycommand.Parameters.Add("#old_cost", SqlDbType.NVarChar).Value = oldcost
mycommand.Parameters.Add("#old_retail", SqlDbType.VarChar).Value = oldretail
mycommand.Parameters.Add("#new_cost", SqlDbType.VarChar).Value = newcost
mycommand.Parameters.Add("#new_retail", SqlDbType.NVarChar).Value = newretail
mycommand.Parameters.Add("#tire_id", SqlDbType.NVarChar).Value = m_introwposition
mycommand.ExecuteNonQuery()
MsgBox("Success")
Catch ex As System.Data.SqlClient.SqlException
MsgBox(ex.Message)
End Try
End If
It won't be initialized this way. Either manually set myCommand.Connection property or create the command using CreateCommand:
myCommand = m_cn.CreateCommand();
You're not connecting the command and the connection.
Try this before executing it:
mycommand.Connection = m_cn;
You can also ask the connection object to create the command object for you, in which case it will set this itself:
Dim mycommand As SqlClient.SqlCommand = Connection.CreateCommand()
Additionally, remember to call Dispose on these objects when you're done with them.

"The ConnectionString property has not been initialized" error in VB.NET

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.

Inserting data into SQL Server database using VB.Net

I am currently using HDI Membership provider and the design looks as shown below:
Now I am trying to create a new user and insert those values into the database as shown below:
Try
Dim connectionString As String = "Data Source=.\sqlexpress;Initial Catalog=HDIMembershipProvider;Integrated Security=True"
Using cn As New SqlConnection(connectionString)
cn.Open()
Dim cmd As New SqlCommand()
cmd.CommandText = "INSERT INTO Users VALUES(#Username,#Password,#Email,#PasswordQuestion,#PasswordAnswer)"
Dim param1 As New SqlParameter()
param1.ParameterName = "#Username"
param1.Value = txtUsername.Text.Trim()
cmd.Parameters.Add(param1)
Dim param2 As New SqlParameter()
param2.ParameterName = "#Password"
param2.Value = txtPassword.Text.Trim()
cmd.Parameters.Add(param2)
Dim param3 As New SqlParameter()
param3.ParameterName = "#Email"
param3.Value = txtEmail.Text.Trim()
cmd.Parameters.Add(param3)
Dim param4 As New SqlParameter()
param4.ParameterName = "#PasswordQuestion"
param4.Value = txtSecurityQuestion.Text.Trim()
cmd.Parameters.Add(param4)
Dim param5 As New SqlParameter()
param5.ParameterName = "#PasswordAnswer"
param5.Value = txtSecurityAnswer.Text.Trim()
cmd.Parameters.Add(param5)
cmd.Connection = cn
cmd.ExecuteNonQuery()
cn.Close()
End Using
Successlbl.show
Successlbl.show.Text = "Regisration Success."
Catch
Errolbl.Show()
Errolbl.Text = "Your account was not created.Please try again."
End Try
Now the problem is the data is not inserting to the database. I would like to know If anyone can point me where I'm going wrong?
Your insert statement is incorrect - since you are not specifying any field names you should be supplying values for all columns.
The fix is to supply the names of the columns you are insert into.
The screenshot also shows that there is a required ApplicationName column, so unless it has a DEFAULT defined, you will need to supply that as well.
Assuming you have a DEFAULT defined on ApplicationName:
cmd.CommandText = "INSERT INTO Users ( Username, Password, Email, PasswordQuestion, PasswordAnswer) VALUES(#Username,#Password,#Email,#PasswordQuestion,#PasswordAnswer)"

Resources