While trying to pass an integer parameter #id to a stored procedure, I get an error da.Fill(ds):
Additional information: Conversion failed when converting the varchar value '#id' to data type int.
I have made sure that integer value is passed and stored procedure contain the correct datatype. What other possibilities are there to rectify this error?
SqlConnection conn = new SqlConnection(cs);
conn.Open();
SqlCommand cmd1 = new SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#id", id);
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);
If you know better, do not use AddWithValue() ... it has to "guess" what datatype you have in your DB based on what you put into the command. It is errorprone and causes unneeded conversions to take place.
Also: use using(..) around disposables, especially when using Database-access as it will close your connections even if exceptions arise - not using using might let some connection stay unclosed.
DataSet ds = new DataSet ();
using (var conn = new SqlConnection (cs))
{
using (var cmd1 = new SqlCommand ("asp_GetTrainingDetail", conn))
{
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#id", System.Data.SqlDbType.BigInt).Value = id;
using (var da = new SqlDataAdapter (cmd1))
{
da.Fill (ds);
}
}
}
Read the link in do not use AddWithValue() for more background infos.
Try this...
SqlConnection conn = new SqlConnection(cs);
conn.Open(); SqlCommand cmd1 = new
SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#id", Int.Parse(id));
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);
Related
In sql I normally execute my procedure using
exec dbo.usp_FCS 'TIMV','serial'
And I tried something somewhat the same in c# but it seems I got this wrong
using (SqlConnection connection = new SqlConnection("Data Source=;Initial Catalog=;User ID=;Password="))
{
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" + "'" + MachineName + " ','serial' " , connection))
{
try
{
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
}
catch (SqlException ex)
{
label6.Visible = true;
label6.Text = string.Format("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
}
}
My question is,how can I give those 2 inputs 'TIMV' and 'serial' of my stored procedure using c#?
Edit:
I tried something like this:
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" , connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#p2", SqlDbType.VarChar).Value = "serial";
try
{ my code...
And it is still not working
The most correct way to add a parameter to an SqlCommand is through the Add method that allows you to specify the datatype of the parameter and, in case of strings and decimals, the size and the precision of these values. In that way the Database Engine Optimizer can store your query for reuse and be a lot faster the second time you call it. In your case I would write
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#mname", SqlDbType.NVarChar, 20).Value = MachineName;
cmd.Parameters.Add("#serial", SqlDbType.NVarChar, 20).Value = "serial";
This assumes that your stored procedure receives two parameters named EXACTLY #mname and #serial, the type of the parameters is NVarChar and the length expected is 20 char. To give a more precise answer we need to see at least the first lines of the sp.
In your code above also the execution of the command is missing. Just creating the command does nothing until you execute it. Given the presence of an SqlDataAdapter I think you want to fill a DataSet or a DataTable and use this object as DataSource of your grid. Something like this
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
yourDataGrid.DataSource = dt;
And if this is an ASP.NET app, also the DataBind call
yourDataGrid.DataBind();
You use the Parameters collection of the SqlCommand class to send parameters to a stored procedure.
Suppose your parameter names are #p1 and #p2 (Please, for your sake, don't use names like this ever) - your c# code would look like this:
using (var cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya", connection))
{
cmd..CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#21", SqlDbType.VarChar).Value = "serial";
try
{
// rest of your code goes here....
Note: use the SqlDbType value that fits the parameters data type.
Try this:
DataSet ds = new DataSet("dts");
using (SqlConnection conn = new SqlConnection
("Data Source=;Initial Catalog=;User ID=;Password="))
{
try
{
SqlCommand sqlComm = new SqlCommand("usp_FCS_GetUnitInfo_Takaya",conn);
sqlComm.Parameters.AddWithValue("#p1", MachineName);
sqlComm.Parameters.AddWithValue("#p2", "serial");
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
catch (Exception e)
{
label6.Visible = true;
label6.Text = string.Format
("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
Here is my code,
Conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
SqlCommand sqlCmd = new SqlCommand("SELECT * from CurrentDataCR ",Conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(ds);
ds.Tables[0].DefaultView.RowFilter = " mst_remote_station_id Like'*9001*'";
Here I am getting Complete row for id 9001. I need only one column value for this id.
DataRow[] rows = ds.Tables[0].Select("mst_remote_station_id Like '%9001%'");
You can do it this way also if you need only one row just select it in the initial query.
Also you should Dispose the SqlDataAdapter after using it ! You can do it with using block
Conn.Open();
DataSet ds = new DataSet();
SqlCommand sqlCmd = new SqlCommand("SELECT * from CurrentDataCR ",Conn);
using(SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(ds);
}
ds.Tables[0].Select("mst_remote_station_id Like '%9001%'");
I don't know if the connection is global but it is bad practice to use global connection, you have connection pool so use separate connection for every query.
when I try to get the Url and pass it to procedure
it didn't passed
string ID = Request.QueryString["URL"];
youtube y = new youtube();
y.URL = ID;
repCurrentVideo.DataSource = y.CurrentVideo();
repCurrentVideo.DataBind();
lblDetails.Text = "no details available about this video";
an error shown to me said
Procedure or function 'currentvideo' expects parameter '#URL', which was not supplied.
Exception Details: System.Data.SqlClient.SqlException: Procedure or function 'currentvideo' expects parameter '#URL', which was not supplied.
and this is the stored procedure invoking code
public DataTable CurrentVideo()
{
CreateConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#URL", URL);
SqlDataAdapter da = new SqlDataAdapter("currentvideo", conn);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
You are never adding the SqlCommand (cmd) to your data adapter
try something like this:
cmd.Parameters.AddWithValue("#URL", URL);
da.SelectCommand = cmd;
or
CreateConnection();
SqlCommand cmd = new SqlCommand("currentvideo", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#URL", URL);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
Also, while we are on the topic of SqlCommands, I believe it is best to wrap them in a using statement as they are of type IDisposable.
using (SqlCommand command = new SqlCommand("currentvideo", conn)) {
...
}
Check out this link to see what it looks like:
http://www.dotnetperls.com/sqlcommand
Edit:
So based on your URL, you are looking for the wrong query string parameter. You need to change the assignment of ID to this:
string ID = Request.QueryString["ID"];
When retrieving a datatable from database using the following code in ASP.Net & C#:
The database is located in my local machine.
string connectionString = #"Data Source=CCS90; Initial Catalog=Ribo; Trusted_Connection=True;";
SqlConnection myConn = new SqlConnection(connectionString);
myConn.Open();
SqlCommand sqlCommand = new SqlCommand("SELECT * FROM PUR_POHEADER WHERE POID = #POID", myConn);
sqlCommand.Parameters.Add("#POID", SqlDbType.Int);
sqlCommand.Parameters["#POID"].Value = Convert.ToInt32(request.ReferenceNo);
DataSet DS = new DataSet();
SqlDataAdapter AD = new SqlDataAdapter(sqlCommand, myConn);
//AD.Fill(DS);
AD.Fill(DS, "POTABLE"); //Error arise at this place
DataTable DT = DS.Tables[0];
myConn.Close();
When compiler comes to the line AD.Fill(DS, "POTABLE");, error occurs at Incorrect syntax near '). What may be the reason?
You create a SqlCommand with a SELECT statement and then you don't use it. What is insertStatement? Surely you should be using sqlCommand.
You may try with
AD.Fill(DS);
instead of
AD.Fill(DS,"PORTABLE");
Also try:
SqlDataAdapter AD = new SqlDataAdapter(sqlCommand);
instead of
SqlDataAdapter AD = new SqlDataAdapter(insertStatement, myConn);
Problem is here:
SqlDataAdapter AD = new SqlDataAdapter(insertStatement, myConn);
replace it with:
SqlDataAdapter AD = new SqlDataAdapter(sqlCommand);
and also you are using this overload i think:
AD.Fill(DS, "NameOfDataTable");
then you can access it like this:
DataTable DT = DS.Tables["NameOfDataTable"];
insetad of using 0 index.
How use WHERE in SqlDataAdapter in C#?
I want get name in a textbox and use that at query but it wont work .
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
string _search_name = txt_search.Text;
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=_search_name ", sqlconnection);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
Prepare the command text and use a parameter for the value of your search.
Then use that command text to initialize a new SqlCommand. Fill the parameter value with AddWithValue and pass the SqlCommand to the constructor of the SqlDataAdapter.
string cmdText = "SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 " +
"FROM tbl_user WHERE dbo.tbl_user.name=#search_name"
SqlCommand cmd = new SqlCommand(cmdText, sqlconnection);
cmd.Parameters.AddWithValue("#search_name", _search_name);
SqlDataAdapter SDA = new SqlDataAdapter(cmd);
The SqlDataAdapter will store your command as the SelectCommand property and will use the passed in SqlCommand to execute the query to retrieve the records from the database.
Keep in mind that AddWithValue is a shortcut with some drawbacks. For example it pass Always a string as a nvarchar parameter with size equal to the actual lenght of the variable. This effectively reduces the performance of the Sql Server Optimizer.
This is a very enlightening article on the issue
So, you were pretty close, you just needed to define a parameter inside the query and then add that parameter. However, in the following code block I've also conveniently recommended a more appropriate approach to using the classes needed to get the data (pun intended). The using statement here ensures that the objects get disposed of properly after you are done using them (man I just can't stop with the puns!)
using (SqlConnection c = new SqlConnection(connString))
{
c.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(
"SELECT dbo.tbl_user.field1, dbo.tbl_user.field2 FROM tbl_user " +
"WHERE dbo.tbl_user.name= #name", c))
{
sda.SelectCommand.Parameters.AddWithValue("#name", txt_search.Text);
DataTable dt = new DataTable();
sda.Fill(dt);
}
}
Try this.
you were using the string directly in the query which will go undetected.
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;
Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=#searchName" , sqlconnection);
SDA.SelectCommand.Parameters.AddWithValue("#searchName", txt_search.Text);
SDA.Fill(dt);
dataGridView1.DataSource = dt;