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.
Related
My code:
string SqlSelectQuery = " Select * From [KTS MANAGMENT] Where STAFF NAME=" + Convert.ToString(textBox1.Text);
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
SqlDataReader dr = cmd.ExecuteReader();
I get this error:
An expression of non-boolean type specified in a context where a condition is expected, near 'NAME'
You should always use parametrized queries to avoid SQL injection - still the #1 vulnerability in computing.
Thus, your code should be something like this:
string connectionString = "......"; // typically read from config file
string query = "SELECT * FROM [KTS MANAGMENT] WHERE STAFF NAME = #Name";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, con)
{
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = textBox1.Text;
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
// read the values from the SQL data reader....
}
con.Close();
}
This approach also avoid the error you have with missing and/or mismatched single or double quotes around strings in a SQL statement ...
I have created a code to take data from one database and place it into a second database, the problem i am having currently is when a field in the database is null it returns an error
"Conversion type 'DBNULL' to type 'String' is not valid"
The code I am using is:
Dim ITN As String = ResultSet.Item( "ItemNumber")
Dim QN As String = ResultSet.Item( "QuoteNumber")
Dim ITD As String = ResultSet.Item( "ItemDescription")
Dim DET As String = ResultSet.Item( "Details")
Dim PR As String = ResultSet.Item("Price")
Hoping someone can assist with this one!!
You can use a ternary statement and check if the Item is null before casting it to a string.
Also in c# you could do something like this:
String value = ResultSet.Item("Price") as String;
The as will convert an invalid reference type to null automatically. For VB.NET:
VB.Net equivalent of C# "As"
I got tired of checking for DBNULL so i wrote a function for that. Depending on the type of database you are working with it really depends but, For efficiency, you'd probably want to use the StringBuilder class rather than string concatenation.
If you use a parameterized query see this link for a very basic introduction to using parameterized queries with Access, you would be able to directly insert the special DBNull value:
Dim myConnection As New OleDbConnection(DBConnection)
Dim Cmd As OleDbCommand = New OleDbCommand()
Cmd.CommandText = "INSERT INTO dbTable (ItemNumber, QuoteNumber, ItemDescription, Details, Price) VALUES (#ITN, #QN, #ITD, #DET, #PR)"
Cmd.Parameters.Add(New OleDbParameter("#ITN", OleDbType.VarChar)).Value = CheckDBNull(ITN)
Cmd.Parameters.Add(New OleDbParameter("#QN", OleDbType.VarChar)).Value = CheckDBNull(QN)
Cmd.Parameters.Add(New OleDbParameter("#ITD", OleDbType.VarChar)).Value = CheckDBNull(ITD)
Cmd.Parameters.Add(New OleDbParameter("#DET", OleDbType.VarChar)).Value = CheckDBNull(DET)
Cmd.Parameters.Add(New OleDbParameter("#PR", OleDbType.VarChar)).Value = CheckDBNull(PR)
DBConnection.Open()
Cmd.ExecuteNonQuery()
this is also good for avoiding nasty SQL Injection. Like I mentioned, depending on the database you are using you might have to use SqlParameter & SqlDbType vs. OleDbParameter & OleDbType but The CheckDBNull function could be a simple as the following:
Private Function CheckDBNull(ByVal s As String) As Object
If Not s Is Nothing And s.Length > 0 Then
Return s
Else
Return System.DBNull.Value
End If
End Function
I hope this helps. please note some of these parameters were just used as an example (myConnection, Cmd, dbTable) as you did not provide db info:
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 would like to know the difference between these 2 notations.
First of all I have a stored procedure
CREATE PROCEDURE AddSomething( #zonename varchar(50), #desc varchar(255), #TheNewId int OUTPUT ) AS
BEGIN
INSERT INTO a_zone(zonename, descr) VALUES(#zonename, #desc)
SELECT #TheNewId = SCOPE_IDENTITY()
END
What is the difference if I add parameters in this manner
SqlCommand Cmd = new SqlCommand("AddSomething", oConn);
Cmd.CommandType = CommandType.StoredProcedure;
SqlParameter oParam1 = Cmd.Parameters.AddWithValue("#zonename", sName);
SqlParameter oParam2 = Cmd.Parameters.AddWithValue("#desc", description);
and
SqlCommand Cmd2 = new SqlCommand("AddSomething", oConn);
Cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.Add("#zonename", SqlDbType.VarChar).Value = zonename.Text.Trim();
cmd2.Parameters.Add("#desc", SqlDbType.VarChar).Value = desc.Text.Trim();
Here are some explanations:
difference between command Add and AddWithValue
Dim cmd as new SqlCommand("SELECT * FROM MyTable WHERE MyDate>#TheDate",conn)
cmd.Parameters.Add("#TheDate",SqlDbType.DateTime).Value="2/1/2007"
vs
cmd.Parameters.AddWithValue("#TheDate","2/1/2007")
"Add forces the conversion from string to date as it goes into the parameter. AddWithValue would have simply passed the string on to the SQL Server.
When using Parameters.Add - the SqlDbType is known at compile time
When using Parameters.AddWithValue the method has to box and unbox the value to find out its type.
Additional benefits of the former is that Add is a bit more code safe
and will assist against SQL injection attacks , code safe in terms
that if you try to pass a value that doesn't match the SqlDb type
defined - the error will be caught in .Net code and you will not have
to wait for the round trip back.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx
Edit:
example to get an Output-Parameter:
C#
cmd.Parameters.Add(new SqlParameter("#TheNewId", SqlDbType.Int, int.MaxValue));
cmd.Parameters("#TheNewId").Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
int theNewID = (int)cmd.Parameters("#TheNewId").Value;
VB.Net
cmd.Parameters.Add(New SqlParameter("#TheNewId", SqlDbType.Int, Int32.MaxValue))
cmd.Parameters("#TheNewId").Direction = ParameterDirection.Output
cmd.ExecuteNonQuery()
Dim theNewID As Int32 = DirectCast(cmd.Parameters("#TheNewId").Value, Int32)
When you use AddWithValue, the datatype will be worked out (as best possible) based on the types of the variables passed to the method - assuming sName and description are string variables, the params will be passed in as NVARCHAR.
I personally prefer the 2nd approach, being explicit with the data types (plus I actually specify the sizes too) so that they are guaranteed to match the sproc definition and avoid any unexpected behaviour.
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.