Oledb Overflow error in ASP.NET 3.5 C# Website - c#

I am getting a strange "Overflow" error while inserting data to my access database. Actually it works fine locally, but not on the server so I think it can be an OS specific error as my local system is a 64-bit Windows 7 but cant say about the server. But even if it is an OS specific problem, it should have broke up with a numeric value being inserted but the data columns in my database are all text, memo and datetime and an auto-number field.
Here is the code:
string cmdd = #"Insert into Alumni_tb (A_Name, Batch, Stream, Adm_No, Email, Address, Profession, Contact_No, Comments, Date_Added, Last_Update_Date, Active)
values (#A_Name,#Batch, #Stream, #Adm_No, #Email, #Address, #Profession,#Contact_No, #Comments, #Date_Added, #Last_Update_Date , #isActive)";
OleDbCommand cmd = new OleDbCommand(cmdd, conn);
cmd.Parameters.AddWithValue("#A_Name", aName);
cmd.Parameters.AddWithValue("#Batch", Batch);
cmd.Parameters.AddWithValue("#Adm_No", admno);
cmd.Parameters.AddWithValue("#Stream", stream);
cmd.Parameters.AddWithValue("#Email", Email);
cmd.Parameters.AddWithValue("#Address", address);
cmd.Parameters.AddWithValue("#Profession", prof);
cmd.Parameters.AddWithValue("#Contact_No", contno);
cmd.Parameters.AddWithValue("#Comments", comments);
cmd.Parameters.AddWithValue("#Date_Added", dateAdded);
cmd.Parameters.AddWithValue("#Last_Update_Date", lastUpdateDate);
cmd.Parameters.AddWithValue("#isActive", true);
conn.Open();
int cnt = 0;
cnt=cmd.ExecuteNonQuery();
if (cnt > 0)
{
//Display Ok Message
return;
}
else
{
//Display Error Message
}
The variable passing values to the params are all string and have been initalized and populated before defining the insert query.
In the database, the columns and datatype are described below.
A_Name is a Text;
Batch is Text;
Stream is Text;
Adm_No is Text;
Email is Text;
Address is Memo;
Profession is Text;
Contact_no is Text;
Comments is Memo;
Date_added is DateTime;
Last_update_date is DateTime;
Active is Yes/No;
I only get an "Overflow" error message, at cmd.ExecuteNonQuery();Please help!!!

I think you should use SqlCommand..
SqlCommand cmd = new SqlCommand(string cmdd = #"Insert into Alumni_tb (A_Name, Batch, Stream, Adm_No, Email, Address, Profession, Contact_No, Comments, Date_Added, Last_Update_Date, Active) values (#A_Name,#Batch, #Stream, #Adm_No, #Email, #Address, #Profession,#Contact_No, #Comments, #Date_Added, #Last_Update_Date , #isActive)
I did not see you used OleDbCommand, sorry..

Related

Trying to insert data to database in c# forms but getting this error message when insert button is hit. Parameter not supplied

Connecting my program to the database but running into this problem.
Error message:
The parameterized query '#first_name nvarchar(1), #last_name nvarchar(1), #email nvarchar(' expects the parameter '#username', which is not supplied.
Absolutely lost not really sure what the error message is saying.
Here's my code to insert the data into SQL Server database tables. Any advice is appreciated.
public bool Insert(userBLL u)
{
bool Success = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
String sql = "INSERT INTO tbl_users (first_name, last_name, email, username, password, contact, address, gender, user_type, added_date, added_by) VALUES (#first_name, #last_name, #email, #username, #password, #contact, #address, #gender, #user_type, #added_date, #added_by)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#first_name", u.first_name);
cmd.Parameters.AddWithValue("#last_name", u.last_name);
cmd.Parameters.AddWithValue("#email", u.email);
cmd.Parameters.AddWithValue("#username", u.username);
cmd.Parameters.AddWithValue("#password", u.password);
cmd.Parameters.AddWithValue("#contact", u.contact);
cmd.Parameters.AddWithValue("#address", u.address);
cmd.Parameters.AddWithValue("#gender", u.gender);
cmd.Parameters.AddWithValue("#user_type", u.user_type);
cmd.Parameters.AddWithValue("#added_date", u.added_date);
cmd.Parameters.AddWithValue("#added_by", u.added_by);
conn.Open();
int rows = cmd.ExecuteNonQuery();
// value of rows will be greater than 0 or else
if (rows > 0)
{
Success = true;
}
else
{
Success = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
return Success;
}
After observing your code, In region(#region Insert data to database) that you shared, I think there was no problem in your code.
Make sure userBLL object is not null that you passed in function Insert. So debug your code one more time.
By observing your code the only reason for this error looks like the userbill object has null value for username . So debug it one time and then share

Trying to insert data into an access database from C#, but it fails, and I have no idea why

After browsing this site for some time, I have been able to make a start on a piece of code that adds information from a set of text boxes into a pre-set database.
Here is that code:
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=[[Rather not release private information, but trust me, this part works]]";
var _ID = LblID.Text;
var _FirstName = TxtUsername.Text;
var _LastName = TxtPassword.Text;
var _DOB = TxtFirstName.Text;
var _Number1 = TxtLastName.Text;
var _Number2 = TxtDOB.Text;
var _Email = TxtNumber2.Text;
var _Username = TxtEmail.Text;
var _Password = TxtNumber1.Text;
using (OleDbConnection conn = new OleDbConnection(connString))
{
OleDbCommand cmd = new OleDbCommand("INSERT into Users ([_ID], [_FirstName], [_LastName], [_DOB], [_Number1], [_Number2], [_Email], [_Username], [_Password]) Values(#ID Number, #First Name, #Last Name, #Date of Birth, #Phone Number 1, #Phone Number 2, #Email, #Username, #Password)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#ID Number", OleDbType.VarChar).Value = _ID;
cmd.Parameters.Add("#First Name", OleDbType.VarChar).Value = _FirstName;
cmd.Parameters.Add("#Last Name", OleDbType.VarChar).Value = _LastName;
cmd.Parameters.Add("#Date of Birth", OleDbType.VarChar).Value = _DOB;
cmd.Parameters.Add("#Phone Number 1", OleDbType.VarChar).Value = _Number1;
cmd.Parameters.Add("#Phone Number 2", OleDbType.VarChar).Value = _Number2;
cmd.Parameters.Add("#Email", OleDbType.VarChar).Value = _Email;
cmd.Parameters.Add("#Username", OleDbType.VarChar).Value = _Username;
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = _Password;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
Its a bit long, but stay with me here.
This code is very similar to one I have found from an answer to a previous question, of course, renaming variables and such to integrate the code into my application.
However, after doing a step by step breakdown of how the application is processing this, it seems to fail here:
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
More specifically, the cmd.ExecuteNonQuery().
It seems that the try stops at this part, and skips straight to the catch.
My question is, what am I doing wrong? How badly have I fuc- messed this up?
If you need any specifics, just comment and I'll respond as soon as I can.
Thanks in advance.
Edit 1: Forgot to add the error message, my apologies.
"Syntax error (missing operator) in query expression '#ID Number'."
Edit 2: Not sure if this should be an edit, but now I'm getting an entirely new problem.
After reading the comments, I have changed the area names (both in the application and in the database), and now I'm getting an entirely new error message.
"The INSERT INTO statement contains the following unknown field name: '_ID'."
I have a feeling it will complain the same for the rest of them.
Sorry about all of the trouble.
Spaces are not allowed in Access SQL without backquotes around them. Since parameter names are not tied to anything in the database, simply remove the spaces from them:
... VALUES (#IDNumber, #FirstName, #LastName, ...)
cmd.Parameters.Add("#IDNumber", OleDbType.VarChar).Value = _ID;
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = _FirstName;
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = _LastName;
"The INSERT INTO statement contains the following unknown field name: '_ID'."
This happens because _ID does not match the name of the column in your database. Unlike parameter names of which you have complete control, column names are part of the database schema, so you need to use the exact name, including any spaces that it may have. Use square brackets for names with spaces:
INSERT INTO Users ([ID Number], [First Name], ... ) ...
As the exception tells you, you are missing a comma in your VALUES list right after the #ID parameter.
For your second error-message: do you have a column in your database-table that is called _ID ?
Next to that, you do not have to close the connection explicitly, since you're already using a using statement for the db-connection.

"Syntax error in INSERT INTO statement" when adding record to Access database

I've searched for hours for a solution to this problem but nothing I've read has helped. I'm getting this error when trying to add this record to an Access database. The file I'm trying to save into is named Cats.accdb, with a table named Cats.
Table column names:
CatId (type: text) CatName (text) Hair (text) Size (text) CareType (text) Notes (text)
AdoptDate (date/time general date), Weight (double), Age (integer) (I've commented any reference to these columns out in the C# code to attempt to debug with just plain old text boxes. At first I thought it was because of something to do with using a DateTimePicker, but it still throws the error after commenting out.)
C# code:
Cat temp = new Cat(txtCatName.Text, txtHair.Text, txtSize.Text, txtCareType.Text, txtNotes.Text);
public string AddCat()
{
string strFeedback = "";
string strSQL = "INSERT INTO Cats (CatName, Hair, Size, CareType, Notes) VALUES (#CatName, #Hair, #Size, #CareType, #Notes)";
OleDbConnection conn = new OleDbConnection();
string strConn = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=Data\Cats.accdb; Persist Security Info=False;";
conn.ConnectionString = strConn;
OleDbCommand comm = new OleDbCommand();
comm.CommandText = strSQL;
comm.Connection = conn;
comm.Parameters.AddWithValue("#CatName", CatName);
comm.Parameters.AddWithValue("#Hair", Hair);
comm.Parameters.AddWithValue("#Size", Size);
comm.Parameters.AddWithValue("#CareType", CareType);
comm.Parameters.AddWithValue("#Notes", Notes);
//comm.Parameters.AddWithValue("#AdoptDate", AdoptDate);
//comm.Parameters.AddWithValue("#Weight", Weight);
//comm.Parameters.AddWithValue("#Age", Age);
{
conn.Open();
strFeedback = comm.ExecuteNonQuery().ToString() + " record has been added successfully!";
conn.Close();
}
catch (Exception err)
{
strFeedback = "ERROR: " + err.Message;
}
return strFeedback;
lblFeedback.Text = temp.AddCat();
Thanks for any help you can give!
Size is a reserved keyword. Add brackets around the name to specify that it's an identifier:
string strSQL = "INSERT INTO Cats (CatName, Hair, [Size], CareType, Notes) VALUES (#CatName, #Hair, #Size, #CareType, #Notes)";
Alternatively, change the field name to something that is not a keyword.
In MS Access OLEDB I believe you use position markers rather than parameter names.
string strSQL = "INSERT INTO Cats (CatName, Hair, Size, CareType, Notes) VALUES (?, ?, ?, ?, ?)";

Insert statement into SQL Server db

I'm developing an ASP.NET MVC Web Application using SQL Server.
I am trying to INSERT a new entry into my database and I don't understand what am I doing wrong.
I get an exception on the line:
command.ExecuteNonQuery();
The code is:
try
{
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=UniversityManager;Integrated Security=True");
using (connection)
{
//SqlCommand command = new SqlCommand(
// "INSERT INTO Students VALUES(#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp);",
// connection);
connection.Open();
String sql = "INSERT INTO Students(Id,Name,Surname,Year,PhoneNumber,Cnp) " +
"VALUES (#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp)";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("#Id", SqlDbType.Int);
command.Parameters["#Id"].Value = 5;
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = collection.Name;
command.Parameters.Add("#Surname", SqlDbType.VarChar);
command.Parameters["#Surname"].Value = collection.Surname;
command.Parameters.Add("#Year", SqlDbType.Int);
command.Parameters["#Year"].Value = collection.Year;
command.Parameters.Add("#PhoneNumber", SqlDbType.VarChar);
command.Parameters["#PhoneNumber"].Value = collection.PhoneNumber;
command.Parameters.Add("#Cnp", SqlDbType.VarChar);
command.Parameters["#Cnp"].Value = collection.Cnp;
command.ExecuteNonQuery();
connection.Close();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Thank you!
YEAR is a reserved keyword for Sql Server. So, if you really have a column with that name, then you need to enclose it in square brackets every time you refer to it. Better change that name
String sql = "INSERT INTO Students(Id,Name,Surname,[Year],PhoneNumber,Cnp) " +
"VALUES (#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp)";
Another possibility is the Id column. If this column has the IDENTITY property set to true, then you should not set a value for it. It is automatically calculated by the database engine.
Looking at your innerexception message, it seems the problem is due to one or more of your parameters contains more text than allowed by the database field size.
You could try something like this (for each varchar parameter)
// Assuming the Name field is defined as varchar(15)
command.Parameters.Add("#Name", SqlDbType.VarChar, 15);
command.Parameters["#Name"].Value = collection.Name;
The String or binary data would be truncated exception means you're trying to insert a value that is too large for one of the columns in your Student table. For example, your Name field has a maximum length of 10 but you're trying to insert a 15 character name.
Check the values you're inserting and see if they're too large for the columns.

I keep crashing with Inserting a record using OleDbConnection and OleDbCommand

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 ( ?, ?, ? )

Categories

Resources