I have a number in C# which is double longitude =1.041970849797e-05.
When I try to insert it into a decimal(9,6) column, I get the error message:
Error converting data type nvarchar to numeric
How do I correctly save the above as a decimal?
C# Application Code:
static void Main(string[] args)
{
double lat=1.041970849797e-05;
insertRecs(lat);
}
private static void insertRecs(double latitude)
{
Int32 rowsAffected = 0;
string connectionString = GetConnectionString();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("dbo.usp_temp", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 90;
try
{
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ep)
{
Console.WriteLine("Exception in Insertrecords ");
Console.WriteLine(ep.Message);
}
}
}
SQL Stored Procedure:
create PROCEDURE [dbo].[usp_temp]
--The parameters for the stored procedure
#latitude decimal(9,6)
AS
BEGIN
insert into temptest(latitude) values(#latitude);
END
Looking at the sample of code you gave us you don't actually map the latitude variable when running the Stored Procedure.
You would need to add a couple of lines like so:
SqlParameter param = cmd.Parameters.Add("#latitude", SqlDbType.Decimal);
param.Direction = ParameterDirection.Input;
param.Value = latitude;
And edited into your code:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("dbo.usp_temp", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 90;
// Map the parameters into the Stored Procedure
SqlParameter param = cmd.Parameters.Add("#latitude", SqlDbType.Decimal);
param.Direction = ParameterDirection.Input;
param.Value = latitude;
try
{
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ep)
{
Console.WriteLine("Exception in Insertrecords ");
Console.WriteLine(ep.Message);
}
}
Related
I have searched for solutions but I can't find one; please help.
I have this code fragment in C#:
using (SqlCommand command = new SqlCommand())
{
command.Connection = openCon;
command.CommandType = CommandType.Text;
command.CommandText = "update logRecords set totalHours = DATEDIFF(HOUR,timeIn,timeOut)";
try
{
openCon.Open();
int recordsAffected = command.ExecuteNonQuery();
MessageBox.Show("Records affected: " + recordsAffected);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
openCon.Close();
GetLogData();
}
}
but it doesn't work. It didn't show the message box in the try block neither the one in the catch block.
Thanks for helping :D
You can access query with parameters, hope this help:
using(var openCon = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand())
{
command.Connection = openCon;
command.CommandType = CommandType.Text;
command.CommandText = "update logRecords set totalHours = DATEDIFF(HOUR,#timeIn,#timeOut)";
try
{
openCon.Open();
command.Parameters.AddWithValue("#timeIN", timeIn);
command.Parameters.AddWithValue("#timeOut", timeOut);
int recordsAffected = command.ExecuteNonQuery();
MessageBox.Show("Records affected: " + recordsAffected);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
GetLogData();
}
First of all I will create Stored procedure and I will update any of my table through procedure.
So, Basic SP will be like below, and I will run it in a Database(SQL).
CREATE PROCEDURE Set_LogRecords_TotalHours
-- Add the parameters for the stored procedure here
#timeIn datetime,
#timeOut datetime
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
UPDATE LogRecords
SET TotalHours = DATEDIFF(HOUR, #timeIn, #timeOut)
-- returns number of rows
SELECT ##ROWCOUNT
END
GO
Now, I will Move to code side.
I will Create a Generic method to call All of mine Stored procedures, see below.
public static DataSet GetRecordWithExtendedTimeOut(string SPName, params SqlParameter[] SqlPrms)
{
DataSet ds = new DataSet();
try
{
//here give reference of your connection and that is "openCon"
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(SPName, conn))
{
command.Parameters.AddRange(SqlPrms);
command.CommandTimeout = 0;
conn.Open();
command.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
try
{
dataAdapter.SelectCommand = command;
dataAdapter.Fill(ds);
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
}
}
}
catch (Exception ex)
{
//Handle Errror
}
return ds;
}
Now at last, call this method from wherever you need to access database.
Over here is the example of calling generic method.
//Add all the parameter that you want to pass to SP, here we have 2 and they are in DAteTime Formate
SqlParameter[] parameters =
{
new SqlParameter { ParameterName = "#timeIn", Value = ValueOf_TimeIN_DateTIME }
new SqlParameter { ParameterName = "#timeOut", Value = ValueOf_TimeOUT__DateTIME}
};
DataSet ds = DAL.GetRecordWithExtendedTimeOut("Set_LogRecords_TotalHours", parameters);
if (ds != null && ds.Tables.Count >= 1 && ds.Tables[0].Rows.Count >= 1)
{
//Debugg ds and you will see the number of records that affected in last update
}
If I calling a stored proc how do i detect that it has completed succesfully on the server as right now im just doing a try catch which is not the best way of doing this.
public bool deleteTeam(Guid teamId)
{
try
{
string cs = ConfigurationManager.ConnectionStrings["uniteCms"].ConnectionString;
SqlConnection myConnection = new SqlConnection(cs.ToString());
// the stored procedure
SqlCommand cmd = new SqlCommand(
"proc_unitecms_deleteTeam", myConnection);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(
new SqlParameter("#ID", teamId));
return true;
} catch(Exception ex)
{
return false;
}
}
You can return the affected rows number and return -1 in case of catch a exception .
You forget the ExecuteNonQuery.
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
Int32 rowsAffected;
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
sqlConnection1.Close();
I'm updating and deleting these tables by stored procedure...
Update query:
ALTER PROCEDURE [dbo].[IssueUpdate]
(#BookID int,
#BookName nvarchar(50),
#DateIssue datetime,
#ReturnDate datetime,
#PersonID int)
AS
UPDATE tblIssue
SET [BookID] = #BookID ,
[BookName] = #BookName,
[DateIssue] = #DateIssue,
[ReturnDate] = #ReturnDate,
[PersonID] = #PersonID
WHERE BookID = #BookID
Update query:
ALTER PROCEDURE [dbo].[Issuedelete]
AS
DELETE FROM tblIssue
C# code to delete from tblIssue:
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
string c = ConfigurationManager.ConnectionStrings["LMS"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("Issuedelete", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
con.Close();
storedproc();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
C# code to update tblIssue:
private void btnupdate_Click(object sender, EventArgs e)
{
try
{
string c = ConfigurationManager.ConnectionStrings["LMS"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("IssueUpdate", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#BookID", SqlDbType.Int);
cmd.Parameters.Add("#BookName", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#DateIssue", SqlDbType.DateTime);
cmd.Parameters.Add("#ReturnDate", SqlDbType.DateTime);
cmd.Parameters.Add("#PersonID", SqlDbType.Int);
cmd.ExecuteNonQuery();
con.Close();
storedproc();
}
catch (Exception ex)
{
Console.WriteLine("SqlError" + ex);
}
}
After compiling, I get an error.
String input was not in a correct format
I tried other ways by changing the parameters with OleDB and SqlDbType... But it's not deleting and updating records... And also having same problem when I'm updating and deleting into tblReturn... Please, help me??? :(
for your update code, Like DonBoitnott mentioned, you need to give values as well:
private void btnupdate_Click(object sender, EventArgs e)
{
try
{
string c = ConfigurationManager.ConnectionStrings["LMS"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("IssueUpdate", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#BookID", SqlDbType.Int).Value = "Enter Value here";
cmd.Parameters.Add("#BookName", SqlDbType.NVarChar, 50).Value = "Enter Value here";
cmd.Parameters.Add("#DateIssue", SqlDbType.DateTime).Value = "Enter Value here";
cmd.Parameters.Add("#ReturnDate", SqlDbType.DateTime).Value = "Enter Value here";
cmd.Parameters.Add("#PersonID", SqlDbType.Int).Value = "Enter Value here";
cmd.ExecuteNonQuery();
con.Close();
storedproc();
}
catch (Exception ex)
{
Console.WriteLine("SqlError" + ex);
}
}
To me it seems that because you don`t add values as pointed out by amit dayama, the SqlDbType, will act up.
if you could try setting the value of #DateIssue and #ReturnDate to DateTime.Now,
and exclude the rest of the parameters for now.
for the rest of the values:
int wil always have a value (o), but DateTime can throw an exception. for varchar i don`t know exactly.
I have a Windows Forms program I was writing at home (I mostly work with ASP.Net so it's been a while) and I'm having trouble executing stored procedure commands.
I create the SqlCommand object from the SqlConnection object and then create the SqlParameter from the SqlCommand. I specify the name, data type, and so on. However, whenever I call SqlCommand ExecuteReader() it's telling me it expects parameters that were not provided. I clearly added them and can see them populated when stepping through in Debug. Any ideas?
Stored procedure:
EXEC dbo.GetTransactions #StartDate = '2015-04-10 18:07:43',
#EndDate = '2015-04-10 18:07:43'
Class DataAccess:
public static DataTable Execute(SqlCommand iCommand) {
DataTable objTable = new DataTable();
try {
iCommand.Connection.Open();
SqlDataReader objReader = iCommand.ExecuteReader();
objTable.Load(objReader);
objReader.Close();
}
catch {
throw;
}
finally {
iCommand.Connection.Close();
}
return objTable;
}
public static SqlCommand CreateCommand(string iProcedureName) {
try {
SqlConnection objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
SqlCommand objCommand = new SqlCommand(iProcedureName, objConnection);
return objCommand;
}
catch {
throw;
}
}
Class TransactionCollection:
private static DataTable Load(DateTime iStartDate, DateTime iEndDate) {
string strProcedureName = "GetTransactions";
SqlCommand objCommand = DataAccess.CreateCommand(strProcedureName);
SqlParameter param = objCommand.CreateParameter();
param.ParameterName = "#StartDate";
param.DbType = DbType.DateTime;
param.Value = iStartDate;
objCommand.Parameters.Add(param);
param = objCommand.CreateParameter();
param.ParameterName = "#EndDate";
param.DbType = DbType.DateTime;
param.Value = iEndDate;
objCommand.Parameters.Add(param);
return DataAccess.Execute(objCommand);
}
You need to tell your SqlCommand that it's executing a stored procedure! You need to set the CommandType of your SqlCommand - see here:
public static SqlCommand CreateCommand(string iProcedureName) {
try {
SqlConnection objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
SqlCommand objCommand = new SqlCommand(iProcedureName, objConnection);
// add this line here!!
objCommand.CommandType = CommandType.StoredProcedure;
return objCommand;
}
catch {
throw;
}
}
I have code to insert data to SQL table.
The columns have such types:
#param1 datetime,
#param2 nvarchar(50),
#param3 int,
#param4 bit,
#param5 int,
#param6 bit,
#param7 bit,
#param8 varchar(20),
#param9 varchar(20)
This is my method:
try
{
using (SqlCommand oleDbCommand = new SqlCommand())
{
// Set the command object properties
oleDbCommand.Connection = new SqlConnection(connectionString);
oleDbCommand.CommandType = CommandType.StoredProcedure;
oleDbCommand.CommandText = "[dbo].[InsertRow]";
// Add the input parameters to the parameter collection
// m.param1 is of DateTime type, m.param2 of string type, m.param3 of int type, etc.
oleDbCommand.Parameters.AddWithValue("#param1", m.param1);
oleDbCommand.Parameters.AddWithValue("#param2", m.param2);
oleDbCommand.Parameters.AddWithValue("#param3", m.param3);
oleDbCommand.Parameters.AddWithValue("#param4", m.param4);
oleDbCommand.Parameters.AddWithValue("#param5", m.param5);
oleDbCommand.Parameters.AddWithValue("#param6", m.param6);
oleDbCommand.Parameters.AddWithValue("#param7", m.param7);
oleDbCommand.Parameters.AddWithValue("#param8", m.param8);
oleDbCommand.Parameters.AddWithValue("#param9", m.param9);
// Open the connection, execute the query and close the connection.
oleDbCommand.Connection.Open();
oleDbCommand.ExecuteNonQuery();
oleDbCommand.Connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
I have two but related questions:
am I passing parameters correctly? Or do I need casts? (please see the column types in the
beginning of the question).
how to correctly handle closing of database? In case also of some exception?
I would do as below
try
{
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("[dbo].[InsertRow]", conn) {
CommandType = CommandType.StoredProcedure }) {
conn.Open();
command.Parameters.Add("#param1", SqlDbType.DateTime).Value = m.param1;
command.Parameters.Add("#param2", SqlDbType.NVarChar, 50).Value = m.param2;
command.Parameters.Add("#param3", SqlDbType.Int).Value = m.param3;
command.Parameters.Add("#param4", SqlDbType.Bit).Value = m.param4;
command.Parameters.Add("#param5", SqlDbType.Int).Value = m.param5;
command.Parameters.Add("#param6", SqlDbType.Bit).Value = m.param6;
command.Parameters.Add("#param7", SqlDbType.Bit).Value = m.param7;
command.Parameters.Add("#param8", SqlDbType.VarChar, 20).Value = m.param8;
command.Parameters.Add("#param9", SqlDbType.VarChar, 20).Value = m.param9;
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
AddWithValue tries to assigns the value by unboxing an object in the c# type based on the database field's type.
try
{
using (var oleDbConnection = new SqlConnection(connectionString))
{
// Set the command object properties
SqlCommand oleDbCommand = new SqlCommand()
oleDbCommand.Connection = oleDbConnection;
oleDbCommand.CommandType = CommandType.StoredProcedure;
oleDbCommand.CommandText = "[dbo].[InsertRow]";
// Add the input parameters to the parameter collection
// m.param1 is of DateTime type, m.param2 of string type, m.param3 of int type, etc.
oleDbCommand.Parameters.AddWithValue("#param1", m.param1);
oleDbCommand.Parameters.AddWithValue("#param2", m.param2);
oleDbCommand.Parameters.AddWithValue("#param3", m.param3);
oleDbCommand.Parameters.AddWithValue("#param4", m.param4);
oleDbCommand.Parameters.AddWithValue("#param5", m.param5);
oleDbCommand.Parameters.AddWithValue("#param6", m.param6);
oleDbCommand.Parameters.AddWithValue("#param7", m.param7);
oleDbCommand.Parameters.AddWithValue("#param8", m.param8);
oleDbCommand.Parameters.AddWithValue("#param9", m.param9);
// Open the connection, execute the query and close the connection.
oleDbCommand.Connection.Open();
oleDbCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
using statement adds itself the correct connection handling after its use.