I am developing a C# VS 2008 / SQL Server 2005 Express website application. I have tried some of the fixes for this problem but my call stack differs from others. And these fixes did not fix my problem. What steps can I take to troubleshoot this?
Here is my error:
System.Data.SqlClient.SqlException was caught
Message="Conversion failed when converting datetime from character string."
Source=".Net SqlClient Data Provider"
ErrorCode=-2146232060
LineNumber=10
Number=241
Procedure="AppendDataCT"
Server="\\\\.\\pipe\\772EF469-84F1-43\\tsql\\query"
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at ADONET_namespace.ADONET_methods.AppendDataCT(DataTable dt, Dictionary`2 dic) in c:\Documents and Settings\Admin\My Documents\Visual Studio 2008\WebSites\Jerry\App_Code\ADONET methods.cs:line 102
And here is the related code. When I debugged this code, "dic" only looped through the 3 column names, but did not look into row values which are stored in "dt", the Data Table.
public static string AppendDataCT(DataTable dt, Dictionary<string, string> dic)
{
if (dic.Count != 3)
throw new ArgumentOutOfRangeException("dic can only have 3 parameters");
string connString = ConfigurationManager.ConnectionStrings["AW3_string"].ConnectionString;
string errorMsg;
try
{
using (SqlConnection conn2 = new SqlConnection(connString))
{
using (SqlCommand cmd = conn2.CreateCommand())
{
cmd.CommandText = "dbo.AppendDataCT";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn2;
foreach (string s in dic.Keys)
{
SqlParameter p = cmd.Parameters.AddWithValue(s, dic[s]);
p.SqlDbType = SqlDbType.VarChar;
}
conn2.Open();
cmd.ExecuteNonQuery();
conn2.Close();
errorMsg = "The Person.ContactType table was successfully updated!";
}
}
}
Here is my SQL stored proc:
ALTER PROCEDURE [dbo].[AppendDataCT]
#col1 VARCHAR(50),
#col2 VARCHAR(50),
#col3 VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #TEMP DATETIME
SET #TEMP = (SELECT CONVERT (DATETIME, #col3))
INSERT INTO Person.ContactType (Name, ModifiedDate)
VALUES( #col2, #TEMP)
END
The input file has 3 columns. The first two are varchars, but the 3rd one is also varchar I think, but it's represented as "3/11/2010". In this input file, a sample row looks like:
"Benjamin|breakfast|3/11/2010".
And I am trying to convert this date field from a string to a datetime here in my SP. Am I going about it the wrong way?
DataRow:
col1|col2|col3
11|A2|1/10/1978
12|b2|2/10/1978
13|c2|3/10/1978
14|d2|4/10/1978
I think Belousov Pavel is correct. Inside your foreach you assign each dictionary item as a parameter. Each of those parameters are defined as being VarChar. With the information provided it is logical to assume the problem is in the stored procedure.
Can you either post the code of the stored procedure or try and recreate the error inside SQL Management Studio by executing the stored procedure there.
UPDATE...
After looking at your stored procedure the code looks correct. I was able to generate the error message you are getting using the following sql code.
declare #col3 varchar(50)
set #col3 = '|3/11/2010'
declare #temp datetime
set #temp = (select convert(datetime,#col3))
Note that the value of #col3 starts with a pipe character. If you remove the pipe character it works correctly.
I would look closer at the values in the dictionary you are getting you parameter values from. There may be an issue with the way you parsed the data.
UPDATE 2
The code below is not confirmed to work but I think I see what you are trying to do. I assume the DataTable you are passing in has data like this:
col1|col2|col3
11|A2|1/10/1978
12|b2|2/10/1978
13|c2|3/10/1978
14|d2|4/10/1978
If this is the case we don't need the dictionary that was passed in originally. I can also assume that you want the stored procedure to be executed once for each row in the DataTable. The below method is similar to what you where doing although it runs the stored procedure for each row.
What I am not sure from you explanation is if the first row of the DataTable contains the names of the columns, if not no worries then. Hope this makes sense, leave more comments if you have questions.
public static string TestMethod(DataTable dt)
{
string connString = "";
string errorMsg = string.Empty;
try
{
//loop through each row of the datatable. Not sure if the column names is a row.
foreach (DataRow row in dt.Rows)
{
using (SqlConnection conn2 = new SqlConnection(connString))
{
using (SqlCommand cmd = conn2.CreateCommand())
{
cmd.CommandText = "dbo.AppendDataCT";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn2;
cmd.Parameters.Add(new SqlParameter() { ParameterName = "#col1", SqlDbType = SqlDbType.VarChar, Value = row[0] });
cmd.Parameters.Add(new SqlParameter() { ParameterName = "#col2", SqlDbType = SqlDbType.VarChar, Value = row[1] });
cmd.Parameters.Add(new SqlParameter() { ParameterName = "#col3", SqlDbType = SqlDbType.VarChar, Value = row[2] });
conn2.Open();
cmd.ExecuteNonQuery();
conn2.Close();
}
}
}
errorMsg = "The Person.ContactType table was successfully updated!";
}
catch
{
}
return errorMsg;
}
Well, if you do this:
SqlParameter p = cmd.Parameters.AddWithValue(s, dic[s]);
p.SqlDbType = SqlDbType.VarChar;
all your parameters will be of type VARCHAR. This might sound smart at first - it's not.
If you pass dates as varchar, you start getting into the messy business of date/time string formats - unless you always use the ISO-8601 format YYYYMMDD which works on any SQL Server installation, and with any locale / language / date setting. Anything else becomes a gamble. Not the whole world uses the MM/DD/YYYY format as in the US, and depending on your SQL Server's language or date format settings, your date might not be recognized, or even misinterpreted. Just don't do it - it's a mess.
Plus, really - if you have a date/time in your C# code - I would strongly recommend you pass that as a SqlDbType.DateTime to your SQL Server stored proc. You're just gonna save yourself endless hours of debugging and messy conversions and stuf.......
Problem is in stored procedure, I think. May be one of input parameters is DateTime, but you wrote VarChar to this parameter.
UPDATE:
As I can see you don't use DataTable dt in your method AppendDataCT.
You wrote that dic contains values [0]:[col1, col1] [1]:[col2, col2] [2]:[col3, col3]. But it's wrong values... your code is
SqlParameter p = cmd.Parameters.AddWithValue(s, dic[s]);
Then you send to col3 value = col3, as I understand.
May be you wanted to write
SqlParameter p = cmd.Parameters.AddWithValue(s, dt[s]);
or something like this...
You need to loop through the rows of the DataTable to get the data - you're adding the values of dic (your column names for month, day, year??) as SqlParameters..... This is what I'm assuming because the question is pretty scattered....
Note: Not completely functioning code -
foreach(DataRow dr in dt.Rows)
{
DateTime date = new DateTime();
foreach(string s in dic.Keys)
{
switch(dic[s])
{
case "Month":
date.Month = dr[dic[s]];
break;
case "Day":
date.Day = dr[dic[s]];
break;
case "Year":
date.Year = dr[dic[s]];
break;
}
}
// If valid date
SqlParameter p = cmd.Parameters.AddWithValue("Date", date);
p.SqlDbType = SqlDbType.DateTime;
}
UPDATE: You will need to handle your own data validation - otherwise, here you go
using (SqlConnection conn2 = new SqlConnection(connString))
{
using (SqlCommand cmd = conn2.CreateCommand())
{
conn2.Open();
foreach(DataRow dr in dt.Rows)
{
SqlParameter col1 = cmd.Parameters.AddWithValue(dic[0], dr[0].ToString());
SqlParameter col2 = cmd.Parameters.AddWithValue(dic[1], dr[1].ToString());
SqlParameter col3 = cmd.Parameters.AddWithValue(dic[2], Convert.ToDateTime(dr[2]));
cmd.ExecuteNonQuery();
}
conn2.Close();
}
}
In my case I had my INSERT query's values in the wrong order:
INSERT INTO my_table(
status --varchar
, created_on --datetime2
) VALUES (
#created_on --datetime2
, #status --varchar
)
Related
I have a problem calling my stored procedure in my database
this is my stored procedure in my database
DELIMITER $$
USE `sample`$$
DROP PROCEDURE IF EXISTS `sp_ReturnAttendanceInfo`$$
CREATE DEFINER=`root`#`192.168.%` PROCEDURE `sp_ReturnAttendanceInfo`(IN uname INT(4), IN daterange DATETIME)
BEGIN
SELECT shift_time.in, shift_time.out, MIN(perf_prog.start_time) AS start_time, MAX(perf_prog.end_time) AS end_time, perf_prog.date FROM perf_prog INNER JOIN Shifts ON perf_prog.emp_id = Shifts.emp_id
INNER JOIN shift_time ON Shifts.id = shift_time.id
WHERE perf_prog.emp_id = uname AND DATE(`date`) >= daterange
GROUP BY `date` ORDER BY `date` ;
END$$
DELIMITER ;
when i call this stored procedure in database query
like this
CALL sp_ReturnAttendanceInfo(0921, '2017-04-02')
it returns an output
but when i call it in my c#
using (MySqlConnection connection = new MySqlConnection(mysqlConnection))
{
connection.Open();
if (connection.State == System.Data.ConnectionState.Open)
{
using (MySqlCommand cmd = new MySqlCommand("sp_ReturnAttendanceInfo", connection))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#uname", username);
cmd.Parameters.AddWithValue("#date", date.ToString("yyyy-MM-dd"));
using (MySqlDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
}
}
}
}
}
i even checked the parametre im passing:
921
2017-04-04
but still i can't solve it. i even search the problem before creating a question, but i can't solve it. the error message is still the same
and this is the error:
Parameter 'daterange' not found in the collection.
at MySql.Data.MySqlClient.MySqlParameterCollection.GetParameterFlexible(String parameterName, Boolean throwOnNotFound)
at MySql.Data.MySqlClient.StoredProcedure.GetAndFixParameter(String spName, MySqlSchemaRow param, Boolean realAsFloat, MySqlParameter returnParameter)
at MySql.Data.MySqlClient.StoredProcedure.CheckParameters(String spName)
at MySql.Data.MySqlClient.StoredProcedure.Resolve(Boolean preparing)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
both the parameters you pass into the stored proc and the parameters that accept those values have to be the same, thus change:
cmd.Parameters.AddWithValue("#date", date.ToString("yyyy-MM-dd"));
to
cmd.Parameters.AddWithValue("#daterange", date.ToString("yyyy-MM-dd"));
I am complete newbie to programming. I have a problem with my program, what I am trying to do is create a register page so that users can register and it will save into the SQL database but I got an error and I dont know what it means, I will paste the whole error message sorry if its not specific. Please explain in simple terms to me if possible thanks.
Here is my code:
protected void registerBtn_Click(object sender, EventArgs e)
{
String conString = #"Data Source=sql-server;Initial Catalog=wa310;Integrated Security=True";
SqlConnection myConnection = new SqlConnection(conString);
string cmd = "INSERT INTO Student( First_Name, Surname, User_ID, Password) VALUES ( '" + fNameTxt.Text + "' , '" + sNameTxt.Text + "','" + userIdTxt.Text + "' ,'" + passwordTxt.Text + "')";
SqlCommand myCommand = new SqlCommand(cmd, myConnection);
try
{
myCommand.Connection = myConnection;
myConnection.Open();
myCommand.ExecuteNonQuery();
Label1.Text = "You have successfully registered";
}
catch (Exception ex)
{
Label1.Text = "Exception in DBHandler" + ex;
}
finally
{
myConnection.Close();
}
}
This is the error I get, again sorry for the long error message:
Exception in DBHandlerSystem.Data.SqlClient.SqlException (0x80131904):
String or binary data would be truncated. The statement has been
terminated. at
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) at
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String
methodName, Boolean async, Int32 timeout, Boolean asyncWrite) at
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1
completion, String methodName, Boolean sendToPipe, Int32 timeout,
Boolean asyncWrite) at
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
OnlineExamCW.Register.registerBtn_Click(Object sender, EventArgs e) in
f:\COMP1551 - Application and Web
Development\OnlineExamCW\OnlineExamCW\Register.aspx.cs:line 31
ClientConnectionId:e08ebbe3-d4be-4a76-a64d-14aadb6e9d4c
Please tell me what this error means. Many thanks.
The error message tells you that something in your input values is too long to be stored in the designated column. Without knowing the size of your columns is difficult to propose a correct solution so, assuming that you have reasonable limits in the database fields like in this hypotethical schema:
First_Name nvarchar(50)
Surname nvarchar(50)
User_ID int
Password nvarchar(16)
then you should limit the max length of your input fields to the same sizes allowed by the datatable fields.
<asp:TextBox ID="fNameTxt" MaxLength="50" Text="" runat="server"/>
.....
and then create your insert command using this approach
protected void registerBtn_Click(object sender, EventArgs e)
{
String conString = "....";
string cmd = #"INSERT INTO Student( First_Name, Surname, User_ID, Password)
VALUES (#first, #surname, #id, #password);"
using(SqlConnection myConnection = new SqlConnection(conString))
using(SqlCommand myCommand = new SqlCommand(cmd, myConnection))
{
myCommand.Parameters.Add(new SqlParameter()
{
ParameterName = "#first",
Value= fNameTxt.Text,
SqlDbType = SqlDbType.NVarChar,
Size = 50
});
myCommand.Parameters.Add(new SqlParameter
{
ParameterName = "#surname",
Value= sNameTxt.Text,
SqlDbType = SqlDbType.NVarChar,
Size = 50
});
myCommand.Parameters.Add(new SqlParameter()
{
ParameterName = "#id",
Value= Convert.ToInt32(userIdTxt.Text),
SqlDbType = SqlDbType.Int
});
myCommand.Parameters.Add(new SqlParameter()
{
ParameterName = "#password",
Value= passwordTxt.Text,
SqlDbType = SqlDbType.NVarChar,
Size = 16
});
myCommand.Connection = myConnection;
myConnection.Open();
if(myCommand.ExecuteNonQuery() > 0)
Label1.Text = "You have successfully registered";
}
}
Notice that in this code I have totally removed the string concatenation approach. This is a very dangerous mode to write sql statements because you could be easily hacked using the Sql Injection technique and your code could fail if someone enters a single quote in the input values (Try for example for a surname like O'Reilly)
There is another point that need a deep redesign. Storing passwords in clear text is considered a very bad practice because a simple look at your database table could reveal the passwords of all your students. But this is a more complex matter. If you are interested search about Password Hashing
It means the data in one or more fields that you are inserting in Student table has more characters than the field allows. Check the length of all fields -First_Name, Surname, User_ID, Password. Either increase the field length in the database or put a limit on data entry page so that the user isn't allowed to enter more than allowed characters in each field.
I'm trying to simply insert data into a table in SQL Server from a C# winforms application.
Currently when the executing the query I'm receiving the error:
Incorrect syntax near 'soAddItems'
Here is my insert code of the class handling my database CRUD operations:
Note: As test data:
itemName = "test"
skuNo = "a123"
itemPrice = 2.99
stockItemToAdd = 3
itemPic = "C:\Users\Name\Pictures\pic.png"**
Code:
public virtual void AddItem(string itemName, string skuNo, double itemPrice, int stockAmountToAdd, string itemPic)
{
using (SqlConnection open = new SqlConnection(connectionString))
{
SqlCommand insertCommand = new SqlCommand("soAddItems", open);
open.Open();
insertCommand.Parameters.Add("#itemName", SqlDbType.NChar).Value = itemName;
insertCommand.Parameters.Add("#skuNo", SqlDbType.VarChar).Value = skuNo;
insertCommand.Parameters.Add("#itemPrice", SqlDbType.Decimal).Value = itemPrice;
insertCommand.Parameters.Add("#instockAmount", SqlDbType.BigInt).Value = stockAmountToAdd;
insertCommand.Parameters.Add("#lastSold", SqlDbType.DateTime).Value = DateTime.Today;
insertCommand.Parameters.Add("#itemPic", SqlDbType.NChar).Value = itemPic;
//***** Error on the execute*****
insertCommand.ExecuteNonQuery();
};
}
SQL Server stored procedure:
ALTER PROC [dbo].[soAddItems]
#itemName nchar,
#skuNo varchar,
#itemPrice float,
#instockAmount bigint,
#lastSold dateTime,
#itemPic varchar
AS
BEGIN
INSERT INTO items (itemName, skuNo, itemPrice, instockAmount, lastSold, itemPic)
VALUES (#itemName, #skuNo, #itemPrice, #instockAmount, #itemPic)
END
Can anyone tell me where I'm going wrong?
You need to tell the SqlCommand command type as stored procedure.
Try this:
insertCommand.CommandType = CommandType.StoredProcedure;
It looks like you forget to assign your SqlCommand.CommandType property.
Because it is Text as a default.
insertCommand.CommandType = CommandType.StoredProcedure;
Besides the missing CommandType.StoredProcedure, you have a second major flaw: if you define a parameter like this: #skuNo varchar - then you get a string of 1 character length!
That's usually not what you want - you should ALWAYS specify a length when defining parameters and variables in T-SQL!
Use: #skuNo varchar(50) or whatever length you need
I am passing 4 Parameters to an asp.net Webservice. This is my Code so far:
Webmethod:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public List<RaumHelper.RAUM> Raum(string RAUMKLASSE_ID, string STADT_ID, string GEBAEUDE_ID, string REGION_ID)
{
return RaumHelper.Raum(RAUMKLASSE_ID, STADT_ID, GEBAEUDE_ID, REGION_ID);
}
Helperclass:
public class RaumHelper
{
public class RAUM
{
public string RaumName { get; set; }
public string RaumID { get; set; }
}
internal static List<RAUM> Raum( string RAUMKLASSE_ID, string STADT_ID, string GEBAEUDE_ID, string REGION_ID)
{
List<RAUM> strasseObject = new List<RAUM>();
using (SqlConnection con = new SqlConnection(#"Data Source=Localhost\SQLEXPRESS;Initial Catalog=BOOK-IT-V2;Integrated Security=true;"))
using (SqlCommand cmd = new SqlCommand(#"SELECT r.BEZEICHNUNG AS BEZEICHNUNG, r.ID AS ID FROM RAUM r WHERE RAUMKLASSE_ID = #Raumklasse_ID OR STADT_ID = #Stadt_ID OR GEBAEUDE_ID = #Gebaeude_ID OR REGION_ID = #Region_ID", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Raumklasse_ID", RAUMKLASSE_ID);
cmd.Parameters.AddWithValue("#Stadt_ID", STADT_ID);
cmd.Parameters.AddWithValue("#Gebaeude_ID", GEBAEUDE_ID);
cmd.Parameters.AddWithValue("#Region_ID", REGION_ID);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
if (rdr["BEZEICHNUNG"] != DBNull.Value && rdr["ID"] != DBNull.Value)
{
strasseObject.Add(new RAUM()
{
RaumName = rdr["BEZEICHNUNG"].ToString(),
RaumID = rdr["ID"].ToString()
});
}
}
}
}
return strasseObject;
}
}
If i invoke that Webmethod with the 4 Parameters, the Method is working fine an i get a LIST of the RaumName's and RaumID's. But if i put only one Parameter iam getting an Error:
System.Data.SqlClient.SqlException: Error converting data type nvarchar to numeric.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.HasMoreRows()
at System.Data.SqlClient.SqlDataReader.ReadInternal(Boolean setTimeout)
at System.Data.SqlClient.SqlDataReader.Read()
The ID's in the Database are stored as Numeric and i passing string. I think that is the problem. But i dont know how to fix this.
I also want that my Query works also with only two or three entered Parameters.
Thank in advance!
Usually it's not a problem to pass a string to a parameter that's numeric, as long as the SQL Server is able to convert the content of the string to a numeric value itself. If that doesn't work, you get this error.
For example: Passing "Hello" to a parameter that's numeric, you get an error. Passing "1234" you don't. Please note that an empty string or a string containing whitespace can not be converted to a numeric value!
However, it should be said that it is not good style to do that. You should make sure that the types you use in your application match the types in the database to avoid problems. Maybe some further detail on why you need to have string types in your application could help.
EDIT 1
To make a parameter optional for the query, the way to go would be the following:
Change your SQL statement to allow optional parameters like WHERE RAUMKLASSE_ID = ISNULL(#Raumklasse_ID, RAUMKLASSE_ID).
Do not add the #Raumklasse_ID parameter if it should be optional or add the value DBNull.Value
You should really consider changing your string properties to nullable types like int?.
EDIT 2
This is how your code could look implementing the changes I suggested in Edit 1:
using (SqlCommand cmd = new SqlCommand(#"SELECT r.BEZEICHNUNG AS BEZEICHNUNG, r.ID AS ID FROM RAUM r WHERE RAUMKLASSE_ID = ISNULL(#Raumklasse_ID, RAUMKLASSE_ID) OR STADT_ID = ISNULL(#Stadt_ID, STADT_ID) OR GEBAEUDE_ID = ISNULL(#Gebaeude_ID, GEBAEUDE_ID) OR REGION_ID = ISNULL(#Region_ID, REGION_ID)", con))
{
con.Open();
if (!String.IsNullOrWhitespace(RAUMKLASSE_ID))
cmd.Parameters.AddWithValue("#Raumklasse_ID", RAUMKLASSE_ID);
else
cmd.Parameters.AddWithValue("#Raumklasse_ID", DBNull.Value);
if (!String.IsNullOrWhitespace(STADT_ID))
cmd.Parameters.AddWithValue("#Stadt_ID", STADT_ID);
else
cmd.Parameters.AddWithValue("#Stadt_ID", DBNull.Value);
if (!String.IsNullOrWhitespace(GEBAEUDE_ID))
cmd.Parameters.AddWithValue("#Gebaeude_ID", GEBAEUDE_ID);
else
cmd.Parameters.AddWithValue("#Gebaeude_ID", DBNull.Value);
if (!String.IsNullOrWhitespace(REGION_ID))
cmd.Parameters.AddWithValue("#Region_ID", REGION_ID);
else
cmd.Parameters.AddWithValue("#Region_ID", DBNull.Value);
...
}
The problem might be that you're not giving anything to infer the data type from as you're not setting the value of the parameter.
Try setting the parameters using the Add method as follows:
cmd.Parameters.Add("#Raumklasse_ID", SqlDbType.Int).Value = RAUMKLASSE_ID;
That way if you don't want to set the value, you can still define the parameter.
See here for more: http://msdn.microsoft.com/en-us/library/wbys3e9s
Convert your string to intger type
cmd.Parameters.AddWithValue("#Raumklasse_ID", Convert.ToInt32(RAUMKLASSE_ID));
cmd.Parameters.AddWithValue("#Stadt_ID", Convert.ToInt32(STADT_ID));
cmd.Parameters.AddWithValue("#Gebaeude_ID", Convert.ToInt32(GEBAEUDE_ID));
cmd.Parameters.AddWithValue("#Region_ID", Convert.ToInt32(REGION_ID));
Do like this
cmd.Parameters.Add("#Raumklasse_ID", SqlDbType.Int);// use here your SQL DataType, if it is numberic than use Numeric.
cmd.Parameters[0].value = Convert.ToInt32(RAUMKLASSE_ID);
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
cmd = new OleDbCommand(sqlQuery, conn);
cmd.CommandText = "INSERT INTO tickets (ProblemIncidentDate, ProblemIncidentTime, user, StateTagNumber, ProblemType, ProblemDescription, ProblemStatus) VALUES (#ProblemDate,#ProblemTime,#userIDNumber,#StateTag,#ProblemType,#ProblemDescription,#ProblemStatus)";
cmd.Parameters.Add("#ProblemDate", OleDbType.Date).Value = labelProblemDate.Text.Trim();
cmd.Parameters.Add("#ProblemTime", OleDbType.DBTimeStamp).Value = labelProblemTime.Text.Trim();
cmd.Parameters.Add("#userIDNumber", OleDbType.Integer).Value = Convert.ToInt32(userID.ToString());
cmd.Parameters.Add("#StateTag", OleDbType.VarChar).Value = textBoxStateTagNumber.Text.Trim();
cmd.Parameters.Add("#ProblemType", OleDbType.VarChar).Value = comboBoxProblemType.SelectedItem.ToString();
cmd.Parameters.Add("#ProblemDescription", OleDbType.VarChar).Value = textBoxProblemDescription.Text.Trim();
cmd.Parameters.Add("#ProblemStatus", OleDbType.VarChar).Value = "Open";
cmd.ExecuteNonQuery(); //At this line exception is generating
conn.Close();
My database is a Microsoft Access 2007
Here are the field types
ID AutoNumber
ProblemIncidentDate Date/Time
ProblemIncidentTime Date/Time
user Number
StateTagNumber Text
ProblemType Text
ProblemDescription Memo
ProblemResolution Memo
ProblemStatus Text
I can't figure out why it's crashing
The console message says
A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Try with the correct datatypes like
cmd.Parameters.Add("#ProblemDate", OleDbType.Date).Value = DateTime.Parse(labelProblemDate.Text.Trim());
cmd.Parameters.Add("#userIDNumber", OleDbType.Integer).Value = Convert.Int32(userID.ToString());
Converted from my comment:
Try putting brackets around [user], it might be keyword. Also, you are passing strings into your Integer and DateTime fields.
I've worked with different OleDb providers and found that some do NOT like named parameters, and instead, just use a "?" as a place-holder for the parameter. Just note that the parameters need to be added in the same sequence as the insert (just like you have), so try changing to..
insert into YourTable( fld1, fld2, fld3 ) values ( ?, ?, ? )