In the Database, I used an assigned ProgName = varchar,MaleCuteOff = int,FemaleCutOff=int, and I'm trying to collect User input for the values, but I'm getting an Error
Conversion from string "INSERT INTO CutOff_Point((ProgN" to type
integer is not valid.
Sub save()
Dim query As String = "INSERT INTO CutOff_Point (ProgName, MaleCutOff, FemaleCutOff) VALUES (#colProg, #colMale, #colFemale)"
Using con As New SqlConnection("Data Source=.;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True")
Using com As New SqlCommand()
With com
.Connection = con
.CommandType = query
.Parameters.AddWithValue("#colProg", cmbProg.SelectedItem.ToString)
.Parameters.AddWithValue("#colMale", txtMaleCut.Text.ToString)
.Parameters.AddWithValue("#colFemale", txtFemaleCut.Text.ToString)
End With
Try
con.Open()
com.ExecuteNonQuery()
Catch ex As SqlException
MessageBox.Show(ex.Message.ToString(), "Saving data Not Complete")
End Try
End Using
End Using
End Sub
This:
.CommandType = query
should be setting Commandtext, not CommandType. Why set those properties like that in the first place, when you can use the constructor?
Using com As New SqlCommand(query, con)
Related
I am a beginner and really need help. I want to display data from the database and assign the values to the textboxes and a combobox on a form, but I get this error
Incorrect syntax near "="
It appears is on this line
myreader = cmd.ExecuteReader
Please - any help?
Sub ref()
Dim conn As New SqlConnection
conn.ConnectionString = ("Data Source=.;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True")
conn.Open()
Dim strsql As String
strsql = "SELECT ProgName,MaleCuteOff,FemaleCutOff from CutOff_Point where ProgName=" + cmbCourse.SelectedItem + ""
Dim cmd As New SqlCommand(strsql, conn)
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
txtFemale.Text = myreader("FemaleCutOff")
txtMale.Text = myreader("MaleCuteOff")
conn.Close()
End Sub
You should always use SQL parameters to pass parameters to SQL - it avoids embarrasing problems like single quotes breaking the query and deliberate SQL injection attacks.
It's probably best to make sure that there is a selected value before trying to use it.
Some things, e.g. database connections, use "unmanaged resources" and it is necessary to use the Dispose() method to make sure that things are cleaned up afterwards. The Using statement is a convenient way to get the computer to take care of that for you.
I didn't see a need for the query to return the value that was passed to it (ProgName).
You will need to adjust the .SqlDbType and .Size to match the database column.
Option Strict On
' ... other code
Sub Ref()
If cmbCourse.SelectedIndex >= 0 Then
Dim sql As String = "SELECT MaleCuteOff, FemaleCutOff FROM CutOff_Point WHERE ProgName = #ProgName"
Dim connStr = "Data Source=.\;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True"
Using conn As New SqlConnection(connStr),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#ProgName", .SqlDbType = SqlDbType.VarChar, .Size = 99, .Value = cmbCourse.SelectedItem})
conn.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
If rdr.HasRows Then
rdr.Read()
txtFemale.Text = rdr.GetInt32(0).ToString()
txtMale.Text = rdr.GetInt32(1).ToString()
End If
End Using
End If
End Sub
P.S. Shouldn't UEW_ADMISSION_CHEAKER be UEW_ADMISSION_CHECKER? It's best to have things spelt correctly as it is easier to type them.
First of all this Block of Code is not OK. You could use :
Using....End Using Method.
SqlCommand.Parameters Property for security issues.
Connection Strings and Configuration Files for security issues.
Allow me to rewrite your Code using the above methods.
Private Sub RetrieveAndDisplayCutOff()
Dim sbMale As New StringBuilder
Dim sbFemale As New StringBuilder
Dim strsql As String =
"SELECT MaleCutOff,FemaleCutOff FROM CutOff_Point WHERE ProgName = #ComboItem"
Using conn As New SqlConnection("Data Source=.;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True"),
CMD As New SqlCommand(strsql, conn)
CMD.Parameters.Add("#ComboItem", SqlDbType.VarChar).Value = ComboBox1.SelectedItem.ToString
conn.Open()
Using MyReader As SqlDataReader = CMD.ExecuteReader
While MyReader.Read 'Returns False if no more rows
'OP mentioned in comments that these fields were int
sbMale.AppendLine(MyReader.GetInt32(0).ToString)
sbFemale.AppendLine(MyReader.GetInt32(1).ToString)
End While
End Using
End Using
txtMale.Text = sbMale.ToString
txtFemale.Text = sbFemale.ToString
End Sub
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
I have a program that uses either a SQL Server database or a MS Access database.
I'm trying to figure out a way to use either of the databases with the same code. As an example you would do the folowing depending on what DB you're using:
SQL Server:
Using cmd As SqlCommand = New SqlCommand(SQLQuery, Connection)
Using rs As SqlDataReader = cmd.ExecuteReader
Do While rs.Read
' Do something
Loop
End Using
End Using
MS Access:
Using cmd As OleDbCommand= New OleDbCommand(SQLQuery, Connection)
Using rs As OleDbDataReader= cmd.ExecuteReader
Do While rs.Read
' Do something
Loop
End Using
End Using
In my case , I could implement something like this:
Dim rs As New Object
Dim con As Object
Dim cmd As Object
If SQL-Server Then
con = TryCast(conSQL-Server, SqlConnection)
cmd = New SqlCommand
rs = TryCast(rs, SqlDataReader)
Else
con = TryCast(conMS-Access, OleDb.OleDbConnection)
cmd = New OleDb.OleDbCommand
rs = TryCast(rs, OleDb.OleDbDataReader)
End If
Try
With cmd
.Connection = con
.CommandText = SQLQuery
rs = .ExecuteReader
End With
Do While rs.Read
' Do something
Loop
Catch ex As Exception
' Handle Error
Finally
If Not rs Is Nothing Then
If Not rs.IsClosed Then rs.Close()
rs.Dispose()
End If
cmd.Dispose()
End Try
but that's a lot of hassle. It would be nice if you could create a custom type to do something like:
If SQL-Server Then
DBCommand = SqlCommand
DBReader = SqlDataReader
Else
DBCommand = OleDbCommand
DBReader = OleDbDataReader
End
Using cmd As DBCommand = New DBCommand(SQLQuery, connection)
Using rs As DBReader = cmd.ExecuteReader
Do While rs.Read
' Do something
Loop
End Using
End Using
Any ideas?
I discovered the answer:
Dim con As IDbConnection
If SQL-Server Then
con = conSQL-Server
Else
con = conMS-Access
End If
Using cmd As IDbCommand = con.CreateCommand()
cmd.CommandText = SQLQuery
Using rs As IDataReader = cmd.ExecuteReader
Do While rs.Read()
' Do something
Loop
End Using
End Using
It's too bad CreateCommand doesn't take parameters.
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.
I am reading data from an sql database and the connection happens but the following error occurs:
{"Index was outside the bounds of the array."}
On this line:
TextBox2.Text = TextBox2.Text & sqRdr.GetValue(22) & vbCrLf
Please help me with this as I have counted all the columns in my table and they have turned out to be exactly (22).
The column ordinal for the datareader is 0 based, so the 22nd column would be sqRdr.GetValue(21)
Your Datareader should be like below to avoid this issue in a case when you have increased/decreased the number of column in future....
DR["ColumnName"]
SqlDataReader's this[string name] looks like:
Public Overrides Default ReadOnly Property Item(name As String) As Object
Get
Return Me.GetValue(Me.GetOrdinal(name))
End Get
End Property
Below is the sample code...
Using con As System.Data.SqlClient.SqlConnection = New SqlConnection("YourConnection string")
con.Open()
Dim cmd As New SqlCommand()
Dim expression As String = "Parameter value"
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Your Stored Procedure"
cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression
cmd.Connection = con
Using dr As IDataReader = cmd.ExecuteReader()
'You code like ....dr["YourColumnName"]
If dr.Read() Then
End If
End Using
End Using