insert statement C# with MS Access - c#

Hi guys I have got a simple insert statement, I know something is missing as when I click the button to insert the data it dose not insert.
any ideas?
protected void saveyear_Click(object sender, EventArgs e)
{
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\ASPNetDB.mdb;Persist Security Info=True");
OleDbDataAdapter da = new OleDbDataAdapter();
da.InsertCommand = new OleDbCommand("INSERT INTO DVD_Infomation (Year) VALUES (#Year)", connection);
{
da.InsertCommand.Parameters.AddWithValue("#Year", Year.Text);
}
connection.Open();
da.InsertCommand.ExecuteNonQuery();
connection.Close();
}

YEAR is a reserved keyword for MS-Access Jet.
If you want to use it as name of your column you should enclose it in square brackets
da.InsertCommand = new OleDbCommand("INSERT INTO DVD_Infomation ([Year]) VALUES (#Year)", connection);
{
da.InsertCommand.Parameters.AddWithValue("#Year", Year.Text);
}
If it is still possible, I suggest to change the name of that column. It will be annoying to stump on this error every time you try to use that column in your statements
As a side note, I would write the code above as
using(OleDbConnection connection = new OleDbConnection(.....))
using(OleDbCommand cmd = new OleDbCommand("INSERT INTO DVD_Infomation ([Year]) VALUES (#Year)", connection))
{
cmd.Parameters.AddWithValue("#Year", Year.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
Adding the using statement around the creation of the connection and the command will ensure a proper closing and disposing of these objects also in case of exceptions and keep your program more resource usage friendly

Never use a Reserved word in your tables, if you can help it. Since YEAR is a Reserved word, you need to use brackets around the name. Preferrably, change the field name in your table to avoid that issue in the future. Similarly, using field names with spaces in them is also frowned upon as it, too, creates problems when referencing them.

Related

How do I delete an entire row from a database

How would I delete a row from a sql database, either with stored procedures or without, right now I have tried without, using a button press.
This is what I have so far, _memberid has been sent over from a differnt form from the database(For context).
private void btnDelete_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = Lib.SqlConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete * From Members where MemberId = " + _memberId;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.DeleteCommand = cmd;
adapter.Fill(MembersDataTable); // Im fairly sure this is incorrect but i used it from old code
DialogResult = DialogResult.OK;
}
If you're trying to do a simple ADO.Net-based delete, then it would be somehting like his:
private void DeleteById(int memberId)
{
// or pull the connString from config somewhere
const string connectionString = "[your connection string]";
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand("DELETE FROM Members WHERE MemberId = #memberId", connection))
{
command.Parameters.AddWithValue("#memberId", memberId);
command.ExecuteNonQuery();
}
}
Use parameter to prevent SQL injection.
There are essentially three main things I'm seeing...
One
You don't need the * in the query. DELETE affects the whole row, so there's no need to specify columns. So just something like:
DELETE FROM SomeTable WHERE SomeColumn = 123
Two
There's no need for a SqlDataAdapter here, all you need to do is execute the query. For example:
cmd.ExecuteNonQuery();
The "non query" is basically a SQL command which doesn't query data for results. Inserts, updates, and deletes are generally "non queries" in this context. What it would return is simply the number of rows affected, which you can use to double-check that it matches what you expect if necessary.
Three
Don't do this:
cmd.CommandText = "Delete From Members where MemberId = " + _memberId;
This kind of string concatenation leads to SQL injection. While it looks intuitively like you're using _memberId as a query value, technically you're using it as executable code. It's less likely (though not impossible) to be a problem for numeric values, but it's a huge problem for string values because it means the user can send you any string and you'll execute it as code.
Instead, use query parameters. For example, you might do something like this:
cmd.CommandText = "Delete From Members where MemberId = #memberId";
cmd.Parameters.Add("#memberId", SqlDbType.Int);
cmd.Parameters["#memberId"].Value = _memberId;
This tells the database engine itself that the value is a value and not part of the executing query, and the database engine knows how to safely handle values.
You could use a DataAdapter, but since you aren't using a datatable, it's just easier to do it without like this:
var sql = "DELETE FROM Members WHERE MemberId=#MemberId";
using(var cmd = new SqlCommand(sql, Lib.SqlConnection))
{
cmd.Connection.Open();
cmd.Parameters.Add("#MemberId",SqlDbType.Int).Value = _memberId;
cmd.ExecuteNonQuery();
}
And if you are using Dapper, you can do this:
Lib.SqlConnection.Execute("DELETE FROM Members WHERE MemberId=#MemberId", new {MemberId=_memberId});
If you are still using DataTables, I would highly recommend you look into using this (or something like this) to simplify your database accesses. It'll make CRUD logic on a database a breeze, and your code will me a lot more maintainable because you can get rid of all the odd needs to do casting, boxing/unboxing, and reduce the chances of runtime bugs because of the use of magic strings that happens so often with DataTables (column names). Once you start working with POCO classes, you'll hate having to use DataTables. That said, there are a few places where DataTables are a better solution (unknown data structures, etc), but those are usually pretty rare.

Data type mismatch in criteria expression - started only recently

I use Access database. This error wasn't occurring 30 minutes ago.
ERROR is:
Data type mismatch in criteria expression.
OleDbConnection con = new OleDbConnection(Utility.GetConnection());
con.Open();
OleDbCommand cmd2 = new OleDbCommand("INSERT INTO Temsilci(isin_adi,isin_tanimi,verildigi_tarih,teslim_tarihi,sorumlu_marka,sorumlu_ajans,revize,Temsilci_isverenid)
values (#isinadi,#isintanimi,#vertarih,#testarih,#smarka,#sajans,#revize,#temsid)", con);
cmd2.Parameters.Add("isintanimi", txtMarkaAdi.Text);
cmd2.Parameters.Add("isinadi", txtisAdi.Text);
cmd2.Parameters.Add("smarka", txtMarkaTemsilcisi.Text);
cmd2.Parameters.Add("sajans", txtAjansTemsilcisi.Text);
cmd2.Parameters.Add("revize", txtSorumluKisiler.Text);
cmd2.Parameters.Add("vertarih", txtverilisTarihi.Text);
cmd2.Parameters.Add("testarih", txtTeslimTarihi.Text);
cmd2.Parameters.Add("temsid", Session["UserID"]);
cmd2.ExecuteNonQuery();
con.Close();
My database columns are:
ID = AutoNumber
isin_adi = Short Text
isin_tanimi = Long Text
verildigi_tarih= Date/Time
teslim_tarihi=Date/Time
sorumlu_marka = Short Text
sorumlu_ajans=Short Text
personel_id=Number
revize=Short Text
is_durum=Short Text
Temsilci_isverenid=Number
I Solved the problem. I realized the rank of parameters was not true. i change my code like that:
OleDbConnection con = new OleDbConnection(Utility.GetConnection());
con.Open();
OleDbCommand cmd2 = new OleDbCommand("INSERT INTO Temsilci(isin_adi,isin_tanimi,verildigi_tarih,teslim_tarihi,sorumlu_marka,sorumlu_ajans,revize,Temsilci_isverenid) values (#isinadi,#isintanimi,#vertarih,#testarih,#smarka,#sajans,#revize,#temsid)", con);
cmd2.Parameters.Add("isinadi", txtisAdi.Text);
cmd2.Parameters.Add("isintanimi", txtMarkaAdi.Text);
cmd2.Parameters.Add("vertarih", txtverilisTarihi.Text);
cmd2.Parameters.Add("testarih", txtTeslimTarihi.Text);
cmd2.Parameters.Add("smarka", txtMarkaTemsilcisi.Text);
cmd2.Parameters.Add("sajans", txtAjansTemsilcisi.Text);
cmd2.Parameters.Add("revize", txtSorumluKisiler.Text);
cmd2.Parameters.Add("temsid", Session["UserID"]);
cmd2.ExecuteNonQuery();
con.Close();
after that i get error like this :
You cannot add or change a record because a related record is required in table 'Personel'.
And i remove the relationship from 2 tables. And now it works normally.
I think access database have some bugs ,and even if code is correct, errors may accuired.
So i will move my database to SQL from ACCESS i think. Thanks guys.

SqlException : Incorrect syntax near '1'

I am currently trying to implement SQL into a project with Unity3D. So far, I was able to do "normal" UPDATE, ADD, DELETE, DROP, ALTER, INSERT".
Trying to go a step further, I am trying to insert prepared statements, using this link as a guide
Here is my code :
SqlConnection sqlConnection = new SqlConnection(Connection.connectionString)
sqlConnection.Open();
SqlCommand cmd = new SqlCommand(null, sqlConnection);
cmd.CommandText = "INSERT INTO IngredientTypes (Name) VALUES (#name)";
SqlParameter nameParam = new SqlParameter("#name", SqlDbType.Text, 155);
nameParam.Value = Name;
cmd.Parameters.Add(nameParam);
cmd.Prepare();
cmd.ExecuteNonQuery();
My table looks like so :
CREATE TABLE IngredientTypes
(
IngredientTypeID INT IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(155)
);
I get this error :
SQLException : Incorrect systax near '1'.
System.Data.SqlClient.SqlConnection.ErrorHandler (System.Object sender, Mono.Data.Tds. Protocol.TdsInternalErrorMessageEventArgs e)
Help please? Thank you in advance.. I can't find where I did wrong.
You can reduce that code quite a bit with no loss of function, and even some important improvements (for example, this will close the connection even if an exception is thrown):
using (var sqlConnection = new SqlConnection(Connection.connectionString))
using (var cmd = new SqlCommand("INSERT INTO IngredientTypes (Name) VALUES (#name)", sqlConnection))
{
cmd.Parameters.Add("#name", SqlDbType.VarChar, 155).Value = Name;
sqlConnection.Open();
cmd.ExecuteNonQuery();
}
I'm not sure what's causing that exception in your existing code, though, because 1 is not used anywhere in that query. I suspect the problem has something to do with SqlDbType.Text, since that is not the correct type to use with a VarChar column, but it seems just as likely there's code somewhere we haven't seen yet that's changing your SQL command text.
Definitely the Prepare() method in your link is not needed for Sql Server. It's inherited here from DbCommand, where it's included because it's an important part of the API for some other databases, but Sql Server has handled this automatically for more than 10 years now.
SqlDbType.Text Is not the same as varchar. I don’t believe Text types have a length you specify.
Could you try below? Using the "using" structure is safer for sql connections by the way, the connection automatically closes when your process is done.
using (SqlConnection sqlConnection = new SqlConnection(Connection.connectionString))
{
SqlCommand command = new SqlCommand("INSERT INTO IngredientTypes (Name) VALUES (#name)", connection);
command.Parameters.Add("#name", SqlDbType.Varchar, 155);
command.Parameters["#name"].Value = Name; //make sure Name is string.
try
{
sqlConnection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I tried your code exactly as it is and found no issue. Though there are few compilation errors (missing ; in line 1 and Name variable should be coming as parameter) but I am sure you know that. If you have posted your table structure and code exactly the same as you have in your project, then there is no problem in this code.

C# error Must declare the scalar variable

I am getting the following error and I have been doing a lot of research online to re-solve but i can't seem to find the right answer , A bit of help would be much appreciated.
Many Thanks
Error: Additional information: Must declare the scalar variable
"#Username#DepartmentName".
//DepartmentName and Username are both foreign key from LoginDetails table and Department table
SqlConnection cn = new SqlConnection(#"Data Source=PRINCENICHOLAS;Initial Catalog=Kids Company IT Asset;Integrated Security=True");
SqlCommand sqlcmdLogin = new SqlCommand("Insert into LoginDetails(Username,Password,PrivilegeCode) Values(#Username,#Password,#PrivilegeCode)", cn);
sqlcmdLogin.Parameters.AddWithValue("#Username", txtEmpFirstName.Text + '.' + txtEmpSurname.Text);
sqlcmdLogin.Parameters.AddWithValue("#Password", txtEmpPassword.Text);
sqlcmdLogin.Parameters.AddWithValue("#PrivilegeCode", cboPrivilege.SelectedItem.ToString());
cn.Open();
sqlcmdLogin.ExecuteNonQuery();
cn.Close();
//Insert Employee Table
SqlCommand sqlcmdEmp = new SqlCommand("Insert into Employee(FirstName,LastName,DOB,Email,PhoneNumber,JobRole,Username,DepartmentName) Values(#FirstName,#LastName,#DOB,#Email,#PhoneNumber,#JobRole,#Username#DepartmentName)", cn);
sqlcmdEmp.Parameters.AddWithValue("#FirstName", txtEmpFirstName.Text);
sqlcmdEmp.Parameters.AddWithValue("#LastName", txtEmpSurname.Text);
sqlcmdEmp.Parameters.AddWithValue("#DOB", dtpEmpDOB.Text);
sqlcmdEmp.Parameters.AddWithValue("#Email", txtEmpEmail.Text);
sqlcmdEmp.Parameters.AddWithValue("#PhoneNumber", txtEmpPhone.Text);
sqlcmdEmp.Parameters.AddWithValue("#JobRole", txtJobRole.Text);
sqlcmdEmp.Parameters.AddWithValue("#Username", txtEmpFirstName.Text + '.' + txtEmpSurname.Text);
sqlcmdEmp.Parameters.AddWithValue("#DepartmentName", cboDeptName.SelectedItem.ToString());
cn.Open();
sqlcmdEmp.ExecuteNonQuery();
cn.Close();​
You forget to seperate your parameter names with , like
#Username, #DepartmentName
in your sqlcmdEmp definition line.
Since you wrote it as #Username#DepartmentName, your program expect the exact name of it.
Use using statement to dispose your SqlConnection and SqlCommand instead of calling .Close() method manually.
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = cn.CreateCommand())
{
// Define your command text
// Add your paramter values
// Open your connection
// Execute your query
}
Don't store your passwords as a plain text. Read: Best way to store password in database
And don't use AddWithValue method. It may generate unexpected results sometimes. Use .Add() method or it's overloads. Read: Can we stop using AddWithValue() already?

Determining if user login already exists in database?

I am building a web application in asp.net using C#. I have the Form where the user should register and then can login. I am having a problem in making the web app know that the name which the user picks is either "already exists" or not. If it already exists it should not insert the same name and display a message saying "user name already exists". I have tried the SqlDataReader but no luck.
protected void Register_Button_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BJ_Player_String"].ToString());
SqlCommand cmd = new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
SqlDataReader data_reader;
String name = TextBox2.Text;
String date = TextBox3.Text;
try
{
conn.Open();
cmd = new SqlCommand("Insert into BJ_Player (Player_Name, D_O_B) Values (#Player_name, #D_O_B)", conn);
cmd = new SqlCommand("Select Player_Name from BJ_Player WHERE Player_Name = #Player_name", conn);
cmd.Parameters.Add("#Player_name", SqlDbType.NVarChar).Value = name;
cmd.Parameters.Add("#D_O_B", SqlDbType.Date).Value = date;
cmd.Connection = conn;
data_reader = cmd.ExecuteReader();
cmd.ExecuteNonQuery();
if (data_reader.HasRows)
{
lblPlayerNameExists.Visible = true;
}
else
{
// do nothing
}
}
Make Player_Name unique in database then it will give you exception when you try to insert. You have to use unique constraint.
You have to give command type also and check you assigned both queries to same cmd object
in your code you're inserting data in your DB and then you are examining that the name is the same or not.
first you should search the name in your DB and then if there isn't any record with that name ,you should add your record.
I usually do it in one of two ways:
Create stored procedure that will check for name uniqueness and insert new record if everything is ok. It should return status as numeric code that you will check.
Check for name uniqueness before saving it using as a part of validation process.
Using the merge statement may help with this. Merge performs insert, update, or delete operations on a target table based on the results of a join with a source table.
Basically it inserts when needed, and updates when needed. Often times referred to as an upsert. but it gets the job done.
Here is a link to a site explaining how to use merge. Looks like a good article.
http://www.kodyaz.com/articles/sql-server-2008-t-sql-merge-statement-example.aspx
If you would like to write a model function to do that then
Leave it for ajax check which is pretty similar to the second
method
Issue "Select username from DB-table" to retrieve
usernames then check the username input against them before
displaying a view to report a problem if any or showing a message to
tell the user that "this name is valid", for example.

Categories