I am using this code to check my database for errors :
Dim cmd As New SqlCommand("DBCC CHECKDB (offpoDb) WITH TABLERESULTS", con)
cmd.ExecuteNonQuery()
But, u see, this command only generates SQL messages.
Is there any way to retrieve the messages in .net ?
Can i show the messages in a MessageBox ?
I've studied InfoMessage but i still fail to understand how to apply it/work with it.
Use a SqlDataReader instead of ExecuteNonQuery to get the recordset returned by TABLERESULTS:
Dim strBuilder As New System.Text.StringBuilder
Using cmd As New SqlClient.SqlCommand("DBCC CHECKDB (offpoDb) WITH TABLERESULTS", con)
Dim reader As SqlClient.SqlDataReader
reader = cmd.ExecuteReader
While reader.Read
strBuilder.AppendLine(CStr(reader("MessageText")))
End While
reader.Close()
End Using
MessageBox.Show(strBuilder.ToString)
To see all columns which are returned, execute the query in SQL Server Management Studio.
If you prefer to use the InfoMessage-event then add a handler and use it like following:
Sub MyMethod()
Using con As New SqlClient.SqlConnection("<yourConnectionString>")
con.Open()
AddHandler con.InfoMessage, AddressOf InfoMessage
Using cmd As New SqlClient.SqlCommand("DBCC CHECKDB (offpoDb)", con)
cmd.ExecuteNonQuery()
End Using
con.Close()
End Using
End Sub
Private Sub InfoMessage(sender As Object, e As SqlClient.SqlInfoMessageEventArgs)
MessageBox.Show(e.Message)
End Sub
Related
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've got a quite expensive stored procedure in my SQL Server database. Launching it from the SQL Server Managment Studio requires some minutes. But I can't launch it via code using SqlCommand.
I've got this code:
spExecQuery = "EXEC [schema].[storedName]"
If I use this vb.NET snippet:
Using sqlCmd As SqlCommand = New SqlCommand(spExecQuery, conn)
sqlCmd.ExecuteNonQuery()
End Using
The script ends with "Timeout expired" error. But if I do:
Using sqlCmd As SqlCommand = New SqlCommand(spExecQuery, conn)
sqlCmd.CommandTimeout = 0
sqlCmd.ExecuteNonQuery()
End Using
The script never ends (it's running from at least 2 hours)... What am I missing? Thank you.
You need to specify first that it's a stored-procedure:
Using sqlCmd As SqlCommand = New SqlCommand(spExecQuery, conn)
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.CommandTimeout = 0
sqlCmd.ExecuteNonQuery()
End Using
You could also use QueueUserWorkItem to let the method run asynchronously, then you don't need to wait until it has finished:
Public Shared Sub ExecuteStoredProcedureAsync()
Threading.ThreadPool.QueueUserWorkItem(
New Threading.WaitCallback(AddressOf ExecuteStoredProcedure)
)
End Sub
Private Shared Sub ExecuteStoredProcedure(threadState As Object)
Dim sw = New Stopwatch()
sw.Start()
Try
' add code or call of long running method here '
Log.WriteInfo(String.Format("ExecuteStoredProcedure(async call) executed successfully, execution-time: {0}.", sw.Elapsed))
Catch ex As Exception
Log.WriteError(String.Format("Exception in ExecuteStoredProcedure (async call), execution-time: {0}.", sw.Elapsed))
End Try
End Sub
It should work if you specify the CmdType.
If still not working, try using the SqlDataReader
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "proc_name"
Dim dr As SqlDataReader = cmd.ExecuteReader
try to add the command type to your sqlcommand
sqlCmd.CommandType = CommandType.StoredProcedure
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()
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())