Below is my code and I get an error at ExecuteNonQuery:
#Name parameter missing.
I have tried many time and even no error during building of program. The stored procedure contains an insert statement with 4 parameters, 3 of varchar type and one integer type as the primary key.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace CompanyMaster
{
public class Master
{
public IEnumerable<Company> Companies
{
get
{
string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
List<Company> companies = new List<Company>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spGetAllCompany", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Company company = new Company();
company.CompanyCode = Convert.ToInt32(rdr["CompanyCode"]);
company.CompanyName = rdr["CompanyName"].ToString();
company.CompanyAddress = rdr["CompanyAddress"].ToString();
company.CompanyMail = rdr["CompanyMail"].ToString();
companies.Add(company);
}
}
return companies;
}
}
public void Addcompany(Company company)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spAddCompany", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
SqlParameter paramCode = new SqlParameter();
paramCode.ParameterName = "#Code";
paramCode.Value = company.CompanyCode;
cmd.Parameters.Add(paramCode);
SqlParameter PName = new SqlParameter("#Name", SqlDbType.VarChar, 50);
//PName.ParameterName = "#Name";
PName.Value = company.CompanyName;
cmd.Parameters.Add(PName);
SqlParameter paramAddress = new SqlParameter();
paramAddress.ParameterName = "#Address";
paramAddress.Value = company.CompanyAddress;
cmd.Parameters.Add(paramAddress);
SqlParameter paramMail = new SqlParameter();
paramMail.ParameterName = "#Mail";
paramMail.Value = company.CompanyMail;
cmd.Parameters.Add(paramMail);
con.Open();
cmd.ExecuteNonQuery();-- error is occurring here
}
}
}
}
Here is my stored procedure:
CREATE PROCEDURE spAddCompany
#Code INT,
#Name NVARCHAR(50),
#Address NVARCHAR(60),
#Mail NVARCHAR(50)
AS
BEGIN
INSERT INTO CompanyMaster (CompanyCode, CompanyName, CompanyAddress, CompanyMail)
VALUES (#Code, #Name, #Address, #Mail)
END
#Name parameter is missing when the code reaches ExecuteNonQuery.
I think your problem has to do with null vs DBNull.Value.
Check if company.CompanyName is null (in c#). If it is, you should pass DBNull.Value instead.
For more information on the difference between the two, read What is the difference between null and System.DBNull.Value?
From Configuring Parameters and Parameter Data Types:
Note
When you send a null parameter value to the server, you must specify DBNull, not null (Nothing in Visual Basic). The null value in the system is an empty object that has no value. DBNull is used to represent null values. For more information about database nulls, see Handling Null Values.
Also, You can add parameters to the command and set their values in a single line of code, like this:
cmd.Parameters.Add("#Name", SqlDbType.NVarChar, 50).Value = company.CompanyName;
This will make your code much shorter and more readable.
Here are the changes I've made to your code that I think should solve your problem:
public void Addcompany(Company company)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (var con = new SqlConnection(connectionString))
{
// SqlCommand also implements the IDisposable interface
using(var cmd = new SqlCommand("spAddCompany", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Code", SqlDbType.Int).Value = company.CompanyCode;
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = company.CompanyName as object ?? (object)DBNull.Value;
cmd.Parameters.Add("#Address", SqlDbType.VarChar, 50).Value = company.CompanyAddress as object ?? (object)DBNull.Value;
cmd.Parameters.Add("#Mail", SqlDbType.VarChar, 50).Value = company.CompanyMail as object ?? (object)DBNull.Value;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
Note the use of the null coalescing operator (??) and the casting to object.
Related
How can this function be modified.
I want to use it to fill in the dataset from sqllite.
error
public void fillDATASET( DataSet ds, string tablename, string query)
{
string dbPath = Path.Combine(
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
"Department.db3");
var conn = new SQLite.SQLiteConnection(dbPath);
using (Mono.Data.Sqlite.SqliteCommand cmd = new SqliteCommand(query, conn))// error conn
{
using (var DataAdapterd = new SqliteDataAdapter(cmd))
{
ds.Clear();
DataAdapterd.Fill(ds, tablename);
}
}
}
This is because you use two different libraries.
var conn = new SQLite.SQLiteConnection(dbPath);
here you used the method in sqlite-net-pcl nuget,
Mono.Data.Sqlite.SqliteCommand cmd = new SqliteCommand(query, conn)
here you want use the method in System.Data.SQLite.Core nuget.
So you need to use a unified.
For example(use System.Data.SQLite.Core nuget):
using System.Data;
using System.Data.SQLite;
public void fillDATASET(DataSet ds, string tablename, string query)
{
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
"Department.db3");
var conn = new SQLiteConnection(dbPath);
using (SQLiteCommand cmd = new SQLiteCommand(query, conn))// error conn
{
using (var DataAdapterd = new SQLiteDataAdapter(cmd))
{
ds.Clear();
DataAdapterd.Fill(ds, tablename);
}
}
}
Can any one please help me for this.
public Dictionary<string,object> UserExistOrNot()
{
Dictionary<string, object> result = new Dictionary<string, object>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
string _userName = "user01";
string _password = "user";
string sqlQuery = "select * from [User] t0 inner join UserProfile t1 on t0.UserId=t1.UserId where t0.UserName='" + _userName + "' and t0.Password='" + _password+"'";
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con);
DataSet ds = new DataSet();
da.Fill(ds, "usertable");
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
result.Add("UserId", dr["UserId"]);
result.Add("UserName", dr["UserName"]);
result.Add("Password", dr["Password"]);
result.Add("Email", dr["Email"]);
result.Add("Mobile", dr["Mobile"]);
result.Add("Gender", dr["Gender"]);
result.Add("Street1", dr["Street1"]);
result.Add("Street2", dr["Street2"]);
result.Add("Street3", dr["Street3"]);
result.Add("Street4", dr["Street4"]);
result.Add("CityId", dr["CityId"]);
result.Add("StateId", dr["StateId"]);
result.Add("Country", dr["Country"]);
}
}
else
return result;
return result;
}
Output displaying like this:
System.Collections.Generic.Dictionary`2[System.String,System.Object]
I want to display the data instead of type
Browser understands pure text, xml or html, but not complex types, so you have to return one of those types, or create a view with model Dictionary and iterate throw keys and vslues to see it.
I have the following statements:
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["DataBaseName"]);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "update Table1 set data = #data where id = #id";
cmd.Parameters.AddWithValue("#data", SqlDbType.VarChar).Value = data;
cmd.Parameters.AddWithValue("#id", SqlDbType.Int).Value = id;
cmd.CommandType = CommandType.Text;
try
{
DataSet ds = new DataSet();
con.Open();
cmd.Prepare();
cmd.ExecuteNonQuery();
return true;
}
When executing cmd.Prepare() I have an error SqlCommand.Prepare method requires all parameters to have an explicitly set type
I read some answers here, but looks like I did as described here
but still have the same problem.
What am I missing?
I have never used asynchronous calls, could some one please provide me a sample how to call a SQL stored procedure from MVC controller ?
public ActionResult ReProcess(string uname)
{
SqlCommand cmd=new SqlCommand();
cmd.Connection = cnn;
cnn.Open();
cmd.CommandText = "dbo.userdetails_sp";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0;
cmd.Parameters.Add("#userId", System.Data.SqlDbType.VarChar).Value = uname; ;
cmd.ExecuteNonQuery();
}
You can use the Task class to encapsulate a method and then run it asyncronously:
http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx
var t = Task.Factory.StartNew(() => DoAction());
Somebody please help me by modying this code.when i retrieve the Login value through stored procedure call, i am getting this error message "Procedure or function 'GetUserLogin' expects parameter '#UserName', which was not supplied."
Here is my code:
public int GetLogin(string UserName, string Password)
{
SqlConnection con = new SqlConnection(str);
SqlDataAdapter da = new SqlDataAdapter("GetUserLogin", con);
SqlCommand com = new SqlCommand("GetUserLogin",con);
com.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
if ((ds.Tables[0].Rows[0].ItemArray[1].ToString() == UserName) && (ds.Tables[0].Rows[0].ItemArray[2].ToString() == Password))
{
return 1;
}
else
{
return 0;
}
}
else
{
return -1;
}
StoredProcedure:
CREATE PROCEDURE GetUserLogin #UserName varchar(50)
AS
select UserName,
Password
From Login where UserName=#UserName
RETURN
Thanks,
Masum
You need to add a UserName parameter to your command. Do something like this after you create your command, but before you execute it:
com.Parameters.Add("#UserName", SqlDbType.VarChar, 50);
com.Parameters["#UserName"].Value = UserName;
Add this before you fill the dataset
cmd.Parameters.AddWithValue("UserName",UserName);