Can someone point me in the right direction? I have not been able to find documentation to help me build a vb api that can read from a SQL Server stored procedure. I currently have an api that works, I was able to test my controller and the methods (GET, POST, ) work. Please let me know how can I read from a .sql file.
The code below is in Calendar Model - Calendar.vb
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim sqlFile As String = "C:\temp\test.sql"
Dim sqlText = File.ReadAllText(sqlFile)
Dim connStr = "Server=.\SQLEXPRESS; Database=testing; Integrated Security=SSPI"
Dim conn = New SqlConnection(connStr)
Dim sqlCmd = New SqlCommand(sqlText, conn)
Try
conn.Open()
sqlCmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Something went wrong: " & ex.Message)
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End Try
End Sub
End Class
If the test.sql execute a run of stored procedure and if it's return a table you can read as this :
Dim reader As SqlDataReader = sqlCmd.ExecuteReader()
While reader.Read()
Console.WriteLine("{0}", reader(0))
End While
If it's return one value use this
intValue =Convert.ToInt32(sqlCmd.ExecuteScalar())
Related
I am a beginner here may I know how to resolve my problem?
I create a program to save images in SQL Server, but this is not working.
Error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Thank you and hopefully for your response guys!
Here is the code:
Imports System.Data.SqlClient
Imports System.IO
Public Class Form5
Dim connection As New SqlConnection("Server=kohyoung-aoi\sa; Database = testDB; Integrated Security = true")
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim command As New SqlCommand("insert into Table_Image1 (Name, Description, Barrowed, Returned, Picture) values (#Name, #Description, #Barrowed, #Returned, #Picture)", connection)
Dim ms As New MemoryStream
PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
command.Parameters.Add("#Name", SqlDbType.VarChar).Value = Txt1.Text
command.Parameters.Add("#Description", SqlDbType.VarChar).Value = Txt2.Text
command.Parameters.Add("#Barrowed", SqlDbType.VarChar).Value = txt3.Text
command.Parameters.Add("#Returned", SqlDbType.VarChar).Value = txt4.Text
command.Parameters.Add("#Picture", SqlDbType.Image).Value = ms.ToArray()
connection.Open()
If command.ExecuteNonQuery() = 1 Then
MessageBox.Show("Image Inserted")
Else
MessageBox.Show("Image not Inserted")
End If
End Sub
I expected to run in normal condition and the output is to save all images into SQL Server.
How can I make my adodc connect faster to my SQL Server? It's taking a minute (so long) before I can view thousand of record in my listview. Please anyone help me.
I'm using this code:
Public Class McheckpaymentNew
Private cn As New ADODB.Connection
Private rs As New ADODB.Recordset
Private Sub McheckpaymentNew_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
cn.ConnectionString = "DSN=database; UID=user; PWD=password"
cn.Open()
rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic
rs.LockType = ADODB.LockTypeEnum.adLockBatchOptimistic
Catch ex As Exception
MsgBox("Failed to Connect!, Please check your Network Connections, or Contact MIS Dept. for assistance.", vbCritical, "Error while Connecting to Database.."
End
End Try
End Sub
End Class
I am writing a simple SQL Server query operation through vb.net application. I am having some strange problems.
This line is giving error:
dr = cmd.ExecuteReader()
This is giving me error "Invalid column name abhishek." Here abhishek is the data I am providing in TextBox1.Text. I am not able to think of any mistake by my side as this is a simple query. I am able to run other queries, like delete queries, on same table in a different form, so its not a database problem.
Any clue what's going wrong?
reginfo is the table name. name is one of the fields.
My complete code is below:
Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Form9
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
cmd.CommandText = "select * from reginfo where name=" + (TextBox1.Text) + ""
Dim dr As SqlDataReader
con.Open()
cmd.Connection = con
dr = cmd.ExecuteReader() '<<< This line is creating problem
If dr.Read() Then
TextBox2.Text = dr(0).ToString()
End If
con.Close()
End Sub
Private Sub Form8_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Data Source=ABHISHEK-PC\SQLEXPRESS;Initial Catalog=locserver;Integrated Security=True;Pooling=False"
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
End Sub
End Class
if the name field is a text field then you need to enclose your textbox in single quotes, but this is bad advice to give. The only good approach to this kind of situations is through a parameterized query
cmd.CommandText = "select * from reginfo where name=#name"
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim dr As SqlDataReader
con.Open()
cmd.Connection = con
dr = cmd.ExecuteReader()
Also, do not keep global objects like a connection or a command. It is always a good practice to instantiate a connection as late as possible and close it as soon as possible, better inside a Using block
Using con = New SqlConnection(...connection string here....)
Using cmd = New SqlCommand("select * from reginfo where name=#name", con)
con.Open()
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Using dr = cmd.ExecuteReader
'.... do you reading
End Using
End Using
End Using
In this way the connection is kept open for the minimum time possible and, also in case of exceptions is closed and disposed appropriately.
I used to follow this method to execute SQL Server agent queries
Public connection As New SqlConnection(connectionstring)
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
Dim sqlquery As String = "insert into tbluserdetails (username,password,usertype) values (#username,#password,#usertype)"
Dim cmd As New SqlCommand(connectionstring, connection)
cmd.Parameters.AddWithValue("#username", txtusername.Text)
cmd.Parameters.AddWithValue("#password", txtpassword.Text)
cmd.Parameters.AddWithValue("#usertype", cbousertype.Text)
Try
connection.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Finally
connection.Close()
End Try
End Sub End Class
Now I want to execute the stored procedure sp_saurav that has 5 parameters. Using same method is it possible? I googled for this but there are very different codes shown.
I would be grateful if someone could help me execute stored procedure with identical code as shown above.
You have to set the CommandType property of the SqlCommand object to the value StoredProcedure and set the procedure name as the value for CommandText property.
Dim connString As String = "connectionstring"
Dim sqlquery As String = "procedure_name"
Using conn As New SqlConnection(connString)
conn.Open()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = sqlquery
cmd.Parameters.AddWithValue("#param1", value1)
cmd.Parameters.AddWithValue("#param2", value2)
cmd.Parameters.AddWithValue("#param3", value3)
cmd.Parameters.AddWithValue("#param4", value4)
cmd.Parameters.AddWithValue("#param5", value5)
cmd.ExecuteNonQuery()
End Using
I use Visual Basic 2010 and Microsoft SQL Server 2008. I have my database and my table and i made the connection (at least i think i did) in VB using only the interface.
What i want to know is how to get data from the database and use it into my VB project. I have of course searched for solutions already but the differences i find only confuse me more. What i need to know are the basics, the tools/objects and procedures to retrieve the data.
What i try to do at the moment is make a simple selection and put that data into a listbox right when the program starts, like this:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SqlConnection1.Open()
SqlConnection1.Close()
End Sub
End Class
1) Create your connection string
Dim connectionString As String = "Data Source=localhost;........."
2) Connect to your Database
Dim connection As New SqlConnection(connectionString)
conn.Open()
3) Create a Command and the query
Dim command As New SqlCommand("SELECT * FROM Product", connection)
Dim reader As SqlDataReader = command.ExecuteReader() //Execute the Query
4) Retrieve your result. There are several ways
Dim dt As New DataTable()
dt.Load(reader)
'Close the connection
connection.Close()
5) Bind to your list box
myListBox.ItemSource = dt
Full code here
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand("Select * from Products", connection)
command.Connection.Open()
SqlDataReader reader = command.ExecuteReader()
End Using
For more info
SQLCommand
SqlConnection1.Open()
using table As DataTable = New DataTable
using command as SqlCommand = New SqlCommand("SELECT blah blah", SqlConnection1)
using adapter As SqlDataAdapter = new SqlDataAdapter(command)
adapter.Fill(table)
end using
end using
for each row As DataRow in table.Rows
' add each listbox item
listbox1.Items.Add(row("column name"))
next
end using
SqlConnection1.Close()