Ok, I'm stumped here - the following code throws an error
Procedure or function 'importsp_CreateDiallerBatch' expects parameter '#BatchName, which was not supplied`
Code:
Dim cmd As SqlCommand = New SqlCommand()
cmd.CommandText = "importsp_CreateDiallerBatch"
cmd.Connection = cnSQL
cmd.Parameters.AddWithValue("#BatchName", BatchName)
Dim IdParameter As SqlParameter = New SqlParameter()
IdParameter.Direction = ParameterDirection.InputOutput
IdParameter.SqlDbType = SqlDbType.Int
IdParameter.Value = -1
IdParameter.ParameterName = "#BatchID"
cmd.Parameters.Add(IdParameter)
cnSQL.Open()
cmd.ExecuteNonQuery()
When debugging the code, BatchName definitely has a value, and checking the parameters collection of cmd right before executing the query shows 2 params, both named and with values set exactly as expected. I must have written code like this a thousand times - am I missing something here?
Ok appears that I forgot the line cmd.CommandType = CommandType.StoredProcedure. Adding this in made it work.
Related
I have a generic update function that takes a datatable, select query and uses this to update the database tables.It is working fine. I need to know is there a way to get back the inserted row's ID (identity field) by changing something in the below code.
Public Function UpdateDataTable_GetID(ByVal dt As DataTable, ByVal SQL As String, ByVal connString As String) As Integer
Dim conn As SqlConnection = Nothing
Dim cmd As SqlCommand
Dim adp As SqlDataAdapter = Nothing
Dim cmdBuilder As SqlCommandBuilder = Nothing
Dim UpdatedID As Integer
If SQL.Length <= 0 Then
Return False
End If
conn = New Data.SqlClient.SqlConnection(connString)
cmd = New Data.SqlClient.SqlCommand
cmd.Connection = conn
cmd.CommandText = SQL
cmd.CommandType = CommandType.Text
adp = New Data.SqlClient.SqlDataAdapter(cmd)
cmdBuilder = New Data.SqlClient.SqlCommandBuilder(adp)
Try
UpdatedID = Convert.ToInt32(adp.Update(dt)) ' What to do here to get the just inserted ID instead of number of records updated
adp.Dispose()
cmdBuilder.Dispose()
Return UpdatedID
Catch ex As System.Data.SqlClient.SqlException
' Closing connection
Return -1
Finally
End try
End function
I am aware of solutions wherein I can append "select scope_identity()" to the insert Command of data adapter's query using designer as well as editing the adapter's insertcommand text and then doing an ExecuteScalar(). I want to know if the generic adapter.Update() can be tweaked to get the inserted row's ID.
you can subscribe to this event in code like this : (C# I dont know VB)
adp.RowUpdated += adapter_RowUpdated;
and write the event yourself :
void adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
{
if (e.StatementType == StatementType.Insert)
{
object id = e.Command.Parameters["#ID"].Value;
e.Row[_identityFieldName] = id;
}
}
In this example the following has been added to the commandtext first :
SET #ID = SCOPE_IDENTITY()
and a private variable _identityFieldName has been filled.
Maybe this can help you.
EDIT: I noticed you also use an SqlCommandBuilder that makes things easier to add the Scope identity :
SqlCommand inserter = new SqlCommand();
inserter = cmdBuilder.GetInsertCommand(true).Clone();
inserter.CommandText += " SET #ID = SCOPE_IDENTITY()";
SqlParameter param = new SqlParameter();
param.Direction = ParameterDirection.Output;
param.Size = 4;
param.DbType = DbType.Int32;
param.ParameterName = "#ID";
inserter.Parameters.Add(param);
adp.InsertCommand = inserter;
I am receiving this error:
Procedure or function 'usp__SingleSelectServerRackName' expects parameter '#chvServerName', which was not supplied.
I looked up the error and did not find any applicable solutions.
I was successfully able to run the Proc and retrieve out put information, and was able to successfully retrieve value of cbserver.valuemember in command window.
Any suggestions to correct this problem?
Here is my code:
Imports System.Data.SqlClient
Try
Dim connString As String = "server=ServerName;database=DatabaseName;trusted_connection=yes"
Using connection As New SqlConnection(connString)
'Create the command and set its properties.
Dim SingleSelectServerRackName As SqlCommand = New SqlCommand
SingleSelectServerRackName.Connection = connection
SingleSelectServerRackName.CommandText = "usp__SingleSelectServerRackName"
SingleSelectServerRackName.CommandType = CommandType.StoredProcedure
'Add the input parameter and set its properties
Dim ParamSingleSelectServerName As New SqlParameter()
ParamSingleSelectServerName.ParameterName = "#chvServerName"
ParamSingleSelectServerName.SqlDbType = SqlDbType.VarChar
ParamSingleSelectServerName.Direction = ParameterDirection.Input
ParamSingleSelectServerName.Value = cbServer.SelectedValue.ToString()
Dim ParamSingleSelectServerRackName As New SqlParameter
ParamSingleSelectServerName.ParameterName = "#numServerRackName"
ParamSingleSelectServerRackName.SqlDbType = SqlDbType.VarChar
ParamSingleSelectServerRackName.Direction = ParameterDirection.Output
ParamSingleSelectServerRackName.Size = 50
'Add the parameters to the Parameters collection
SingleSelectServerRackName.Parameters.Add(ParamSingleSelectServerName)
SingleSelectServerRackName.Parameters.Add(ParamSingleSelectServerRackName)
'Open database connection
connection.Open()
'Execute data reader
Dim readerSingleSelectServerRackName As SqlDataReader = SingleSelectServerRackName.ExecuteReader()
readerSingleSelectServerRackName.Close()
cbRackName.ValueMember = SingleSelectServerRackName.Parameters("#numServerRackName").Value.ToString
'Close database connection
connection.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
MsgBox(ex.StackTrace)
End Try
Proc:
CREATE Procedure usp__SingleSelectServerRackName
(
#chvServerName AS varchar(50), ---Input variable #chvServerName displays
#numServerRackName AS varchar(50) OUTPUT ---Output variable #numServerRackName
)
AS Begin
IF #chvServerName is null or len(ltrim(#chvServerName)) = 0 ---Check for null value
RAISERROR('Servername cannot be blank.',16,1)
SELECT Rcknm.nm
FROM Rcknm
INNER JOIN Srvr
on srvr.fk_rcknm = Rcknm.ID
WHERE srvr.nm = #chvServerName
End
Looks like you missed something on your copy/paste of parameters.
ParamSingleSelectServerName.ParameterName = "#numServerRackName"
ParamSingleSelectServerName.ParameterName = "#chvServerName"
Your second parameter is overwriting your first. Try this instead.
ParamSingleSelectServerRackName.ParameterName = "#numServerRackName"
Name of the 2nd parameter is same so overwriting it
Look at these two lines
Dim ParamSingleSelectServerRackName As New SqlParameter
ParamSingleSelectServerName.ParameterName = "#numServerRackName"
You are declaring the second parameter, but then you set the name intended for the second parameter to the first parameter.
That's the missing parameter, you have no more a parameter called #chvServerName
You are really making your life difficult. Why not just calling the twos #Rack and #Server ?
There are 10 rows in primary_student_table.
When I execute the following code, the result was -1.
Dim count As Int16
con.Open()
query = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1 "
cmd = New SqlCommand(query, con)
count = cmd.ExecuteNonQuery
MsgBox(count)
con.Close()
What's the problem in the above code?
You should be using ExecuteScalar() rather than ExecuteNonQuery() because you are fetching a value.
count = Convert.ToInt16(cmd.ExecuteScalar())
MsgBox(count.ToString())
SqlCommand.ExecuteScalar Method
For proper coding
use using statement for proper object disposal
use try-catch block to properly handle exceptions
Example Code:
Dim connStr As String = "connection string here"
Dim query As String = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1"
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand()
With cmd
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
End With
Try
conn.Open()
Dim count As Int16 = Convert.ToInt16(cmd.ExecuteScalar())
MsgBox(count.ToString())
Catch(ex As SqlException)
' put your exception here '
End Try
End Using
End Using
The solution is to replace
count = cmd.ExecuteNonQuery
with
count = cmd.ExecuteScalar
Like Robert Beaubien said in his comments
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=1234;database=dblms"
Dim READER As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "Select * from dblms.accounts"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
the value in count will be the number of rows in a table :) hope this helped
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)"
I am trying to retrieve some rows from the database using simple SELECT statement in SQL and displaying them in a Data Grid, Now what I have to do is to multiply the retrieved values with some factor and then display it. I am trying to achieve it the following way:
I have declared PerDoseSize1 as a double variable which gets its value from a function. I am not able to do it this way.
It gives me an error saying "PerDoseSize1 is not a valid column"
public void FillDG1(string Chemical_Name0, string Chemical_Name1, string Chemical_Name2, string Chemical_Name3,double PerDoseSize1)
{
objDs.Clear();
string connString ="Data Source=dk1;Integrated Security=True";
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT [Chemical Name],([GWP])*(perdosesize) AS GlobalWarming, ([ODP])*(perdosesize) AS OzoneDepletion, [WDP] AS WaterDepletion ,[FDP] AS FossilDepletion FROM [Surfactants$] WHERE ([Chemical Name] IN ( #ChemicalName0, #ChemicalName1,#ChemicalName2 ,#ChemicalName3)) ";
cmd.Parameters.AddWithValue("#ChemicalName0",Chemical_Name0);
cmd.Parameters.AddWithValue("#ChemicalName1", Chemical_Name1);
cmd.Parameters.AddWithValue("#ChemicalName2", Chemical_Name2);
cmd.Parameters.AddWithValue("#ChemicalName3", Chemical_Name3);
cmd.Parameters.AddWithValue("#perdosesize", PerDoseSize1);
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
dAdapter.Fill(objDs);
DataTable myDataTable = objDs.Tables[0];
DG1.DataContext = objDs.Tables[0].DefaultView;
cmd.ExecuteNonQuery();
MessageBox.Show(ChemicalName0,ChemicalName1);
con.Close();
}
It still doesn't seem to work, Is it still wrong? Please help!
The way you have written it:
"SELECT ([GWP])*(PerDoseSize1) AS GlobalWarming, ([ODP])*(PerDoseSize1)
Will not work because the function argument you're passing in won't be substituted in your SQL.
So you can try creating a Parameter argument for PerDoseSize1 and pass it into the SQL, like you're doing with AddWithValue.
I have declared PerDoseSize1 as a
double variable which gets its value
from a function
So what? How does that get into the SQL? So far there is NOTHING saying this. YOU have to put it into the SQL and assign it to a parameter. It wont magically hook up.