Disconnected ADO.Net mode, load from Datable to Sql Table - c#

I have two Databases Movies(id, name) and SessionsCinema(id, SessionTime, movie, hall, price).
id - is auto increment row.
I work in ado.net Disconnected mode with ms sql database.
I want to save settings to sql table.
Changes to table "Movies" is ok, but with table "SessionsCinema" there are some errors.
//connection start
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "MYPC\SQLEXPRESS";
builder.InitialCatalog = "Cinema";
builder.IntegratedSecurity = true;
SqlConnection conn = new SqlConnection(builder.ConnectionString);
//connection end
//Movies start
SqlCommand inscmd = new SqlCommand();
inscmd.CommandText = "Insert into Movies (name) values(#name); select id = ##IDENTITY from Movies";
inscmd.Connection = conn;
inscmd.Parameters.Add("#name", SqlDbType.NVarChar, 250, "name");
SqlDataAdapter adapter = new SqlDataAdapter(inscmd);
adapter.InsertCommand = inscmd;
adapter.Update(Movies);
//Movies end
//SessionsCinema start
inscmd = new SqlCommand();
inscmd.CommandText = "Insert into SessionsCinema (SessionTime, movie, hall, price) values(#SessionTime, #movie, #hall, #price); select id = ##IDENTITY from SessionsCinema";
inscmd.Connection = conn;
inscmd.Parameters.Add("#SessionTime,#movie,#hall,#price", SqlDbType.NVarChar, 250, "SessionTime,movie,hall,price");
adapter = new SqlDataAdapter(inscmd);
adapter.InsertCommand = inscmd;
adapter.Update(SessionsCinema);
//SessionsCinema end

You must look at closer to SqlParameterCollection.Add signature.
//SessionsCinema start
inscmd = new SqlCommand();
inscmd.CommandText = "Insert into SessionsCinema (SessionTime, movie, hall, price) values(#SessionTime, #movie, #hall, #price); select id = ##IDENTITY from SessionsCinema";
inscmd.Connection = conn;
inscmd.Parameters.Add("#SessionTime, SqlDbType.NVarChar, 250).Value = SessionTime;
inscmd.Parameters.Add("#movie", SqlDbType.NVarChar, 250).Value = movie;
inscmd.Parameters.Add("#hall", SqlDbType.NVarChar, 250).Value = hall;
inscmd.Parameters.Add("#price", SqlDbType.NVarChar, 250).Value = price;
adapter = new SqlDataAdapter(inscmd);
adapter.InsertCommand = inscmd;
adapter.Update(SessionsCinema);
//SessionsCinema end

Your first command works because it has only one parameter and you define one .Add method for it. That's ok.
But your second command has 4 parameter and you can't add 4 parameter in just one .Add method.
You need to add them seperatly with SqlParameterCollection.AddWithValue like;
inscmd.Parameters.AddWithValue("#SessionTime, SessionTime);
inscmd.Parameters.AddWithValue("#movie", movie);
inscmd.Parameters.AddWithValue("#hall", hall);
inscmd.Parameters.AddWithValue("#price", price);

This line is wrong:
inscmd.Parameters.Add("#SessionTime,#movie,#hall,#price", SqlDbType.NVarChar, 250, "SessionTime,movie,hall,price");
You need a separate Parameters.Add() call for each of the parameters in that list. It should look something like this:
inscmd.Parameters.Add("#SessionTime", SqlDbType.NVarChar, 250).Value = SessionTime;
inscmd.Parameters.Add("#movie", SqlDbType.Int).Value = movie;
inscmd.Parameters.Add("#hall", SqlDbType.Int).Value = hall;
inscmd.Parameters.Add("#price", SqlDbType.Money).Value = price;
Also, check your parameter from your first command. It looks like you made the same mistake there.

Related

SQL Server CE executes the same prepared statement no matter what

I'm trying to insert some data read from XML files into my database. The problem is that it only executes one prepared statement (the first one i defined) and this causes errors.
This works:
conn = getConnection();
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO ra_gestiuni ([denumire],[id_ra]) Values(#denumire,#id_ra)";
SqlCeParameter numeParam = new SqlCeParameter("#denumire", SqlDbType.NVarChar, 100);
numeParam.Value = denumire;
cmd.Parameters.Add(numeParam);
SqlCeParameter idRAParam = new SqlCeParameter("#id_ra", SqlDbType.Int);
idRAParam.Value = idRA;
cmd.Parameters.Add(idRAParam);
cmd.Prepare();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
This does not work anymore:
conn = getConnection();
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO ra_active ([denumire],[gestiune],[utilizator],[tip_activ],[nr_invetar],[categorie_activ],[patrimoniu],[id_ra]) Values(#denumire,#gestiune,#utilizator,#tip_activ,#nr_invetar,#categorie_activ,#patrimoniu,#id_ra)";
SqlCeParameter numeParam = new SqlCeParameter("#denumire", SqlDbType.NVarChar, 100);
numeParam.Value = denumire;
cmd.Parameters.Add(numeParam);
SqlCeParameter gestiuneParam = new SqlCeParameter("#gestiune", SqlDbType.Int);
gestiuneParam.Value = gestiune;
cmd.Parameters.Add(gestiuneParam);
SqlCeParameter utilizatorParam = new SqlCeParameter("#utilizator", SqlDbType.Int);
utilizatorParam.Value = utilizator;
cmd.Parameters.Add(utilizatorParam);
SqlCeParameter nrInventarParam = new SqlCeParameter("#nr_inventar", SqlDbType.NVarChar);
nrInventarParam.Value = nrInventar;
cmd.Parameters.Add(nrInventarParam);
SqlCeParameter categorieActivParam = new SqlCeParameter("#categorie_activ", SqlDbType.NVarChar);
categorieActivParam.Value = categorieActiv;
cmd.Parameters.Add(categorieActivParam);
SqlCeParameter patrimoniuParam = new SqlCeParameter("#patrimoniu", SqlDbType.Int);
patrimoniuParam.Value = patrimoniu;
cmd.Parameters.Add(patrimoniuParam);
SqlCeParameter tipActivParam = new SqlCeParameter("#tip_activ", SqlDbType.Int);
tipActivParam.Value = tipActiv;
cmd.Parameters.Add(tipActivParam);
SqlCeParameter idRAParam = new SqlCeParameter("#id_ra", SqlDbType.Int);
idRAParam.Value = idRA;
cmd.Parameters.Add(idRAParam);
cmd.Prepare();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
I get this exception:
The column name is not valid [ Node name (if any) = ,Column name = gestiune ]
This happens because it tries to insert in the previous table (from the previous prepared statement). This is insane, I haven't found any solution to this.
What I see is the parameter #nr_inventar does not exists in your command text (you have #nr_invetar there). Also if you really need to prepare the command before executing, you should set a size for all nvarchar parameters, like you did for #denumire.

Basic method to export cells values from GridView to SQL table

I need to read i little course about how to export a gridView in DevExpress to a SQL table..
like the values First Name, Father Name, Last Name to a table Employee and i have many rows..
how can I loop into every row and send data to the database..
Thx in advance
I tried this code:
string sql = #"INSERT INTO Emp (#FName, #MName,#LName, #Code, #TaxNb, #SSN, #EmploymentType, #DOB, #MarStat, #RegNum, #BadgeNum, #HireDate, #TaxSince, #HireSince, #ArEmpName, #ArFatherName, #ArLastName, ArPayUnit)";
DataTable table = new DataTable();
try
{
SqlConnection connection = new SqlConnection(#"workstation id = PC-PC; user id=sa;Password=sapassword; data source=pc-pc; persist security info=True;initial catalog=CleanPayrollTest2");
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.InsertCommand = command;
connection.Open();
// for (int i =0; i< gridView3.RowCount; i++)
//{
//command.Parameters.Add(#FirstName, gridView3.GetRowCellValue(i,gridView3.Columns));
//adapter.InsertCommand.ExecuteNonQuery();
//}
SqlParameter[] MyParams = new SqlParameter[28];
MyParams[0] = new SqlParameter("#FName", SqlDbType.VarChar, 20);
MyParams[0].SourceColumn = FirstName;
command.Parameters.Add("#FName", SqlDbType.VarChar, 20);
MyParams[1] = new SqlParameter("#MName", SqlDbType.VarChar, 20);
MyParams[1].SourceColumn = FatherName;
MyParams[2] = new SqlParameter("#LName", SqlDbType.VarChar, 20);
MyParams[2].SourceColumn = LastName;
From SqlDataAdapter Class:
The SqlDataAdapter, serves as a bridge between a DataSet and SQL
Server for retrieving and saving data.
In the scenario you described, there is no such need for a "bridge". You just use a SqlCommand, add the collection of SqlParameter to it, and then call ExecuteNonQuery() to perform the insert.
using(SqlConnection connection = new SqlConnection(#"workstation id = PC-PC; user id=sa;Password=sapassword; data source=pc-pc; persist security info=True;initial catalog=CleanPayrollTest2"))
{
using(SqlCommand command = new SqlCommand(sql, connection))
{
try
{
connection.Open();
for (int i =0; i< gridView3.RowCount; i++)
{
SqlParameter parameter = new SqlParameter();
// TODO: handle name accordingly (MName, LName etc.)
parameter.ParameterName = "#FName";
// TODO: handle type accordingly
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
// TODO: use the field name accordingly
parameter.Value = Convert.ToString(gridView3.GetRowCellValue(i, "FieldName"));
// add the parameter to the command
command.Parameters.Add(parameter);
}
command.ExecuteNonQuery();
}
catch(Exception)
{
// TODO: handle the exception
}
}
}
Remark: you should dispose your SQL related objects in the code - a convenient way to do that is to use using statements.

SQL DataTable Update?

I'm not sure, but I think I may have taken a wrong path here. I am trying to update my customer table on my SQL Server. I Connected with a SQLDatareader and then loaded that into my Datatable. I have made all the changes I wanted and now I can't figure out how to get the changes back up. I thought that the "myDataTable.AcceptChanges();" would trigger that to happen but it doesn't.
SqlConnection myConnection = new SqlConnection();
SqlCommand myCommand;
DataTable myDataTable;
SqlDataReader myReader;
myCommand = new SqlCommand();
myCommand.CommandText = " SELECT * FROM customer";
myCommand.CommandType = CommandType.Text;
myCommand.Connection = myConnection;
myCommand.Connection.Open();
myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
myDataTable = new DataTable();
myDataTable.Load(myReader);
// Make Data changes here
myDataTable.AcceptChanges();
MyDataTable.Dispose();
MyCommand.Dispose();
MyConnection.Dispose();
You can use a TableAdapter to commit your changes back to the database. Check out this link for details.
TableAdapter.Update()
In such case you need to use a DataAdapter which has an Update property that takes your Update Query Command.
Even you can use Command Builder and then get the UpdateCommand from CommandBuilder.
Sample Code from MSDN
SqlDataAdapter catDA = new SqlDataAdapter("SELECT CategoryID, CategoryName FROM Categories", nwindConn);
catDA.UpdateCommand = new SqlCommand("UPDATE Categories SET CategoryName = #CategoryName " +
"WHERE CategoryID = #CategoryID" , nwindConn);
catDA.UpdateCommand.Parameters.Add("#CategoryName", SqlDbType.NVarChar, 15, "CategoryName");
SqlParameter workParm = catDA.UpdateCommand.Parameters.Add("#CategoryID", SqlDbType.Int);
workParm.SourceColumn = "CategoryID";
workParm.SourceVersion = DataRowVersion.Original;
DataSet catDS = new DataSet();
catDA.Fill(catDS, "Categories");
DataRow cRow = catDS.Tables["Categories"].Rows[0];
cRow["CategoryName"] = "New Category";
catDA.Update(catDS);
MSDN Link

update table in database from datatable

I load data from database table like this...
using (view_adapter = new SqlDataAdapter("select * from TVServiceProvider", connection_string))
{
using (dt = new DataTable())
{
view_adapter.Fill(dt);
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Columns[i].ColumnName.Substring(0, 2).Equals("id"))
dt.Columns[i].ReadOnly = false;
}
bs.DataSource = dt;
}
}
Where SqlDataAdapter view_adapter and DataTable dt. To apply changes to database I've created method
void View_Adapter_Click(object sender, EventArgs e)
{
try
{
view_adapter.Update(dt);
dt.AcceptChanges();
}
catch (Exception exc)
{
this.radLabelElement1.Text = exc.Message;
}
}
But when I click the button I've got an exception. It requires update command. Where and what command I should use?
You must create UpdateCommand and DeleteCommand for you view_adapter.
EDIT:
The code must look like this:
SqlDataAdapter view_adapter = new SqlDataAdapter();
view_adapter .SelectCommand = new SqlCommand(queryString, connection);
view_adapter .UpdateCommand = new SqlCommand(updateCommadString, connection);
view_adapter .DeleteCommand = new SqlCommand(deleteCommadString, connection);
using (SqlConnection connection = new SqlConnection(connectionString))
{
view_adapter.Fill(dt);
return dt;
}
Well, something is wrong or not clear in your code.
The view_adapter variable is initialized within a using block statement.
Thus, when exiting from the using block, the view_adatpter will be disposed by the framework and unusable in the click event. (like you have never called new to initialize it).
I suspect that you have another problem here. Using statement
A part from this, to automatically create the UpdateCommand, InsertCommand and DeleteCommand required to perform CRUD operations with a DataAdapter you could use a SqlCommandBuilder.
(This is possible only if you use one table in the select statement and that table has a primary key defined)
So to summarize everything:
string queryString = "select * from TVServiceProvider";
view_adapter = new SqlDataAdapter(queryString, connection_string);
SqlCommandBuilder builder = new SqlCommandBuilder(view_adapter)
builder.GetUpdateCommand(); // Force the building of commands
view_adapter.Fill(dt);
then your click event should works as is now.
This code is not related to yours, but may help you, If you give it a look. I got it from MSDN
public static SqlDataAdapter CreateCustomerAdapter(
SqlConnection connection)
{
SqlDataAdapter adapter = new SqlDataAdapter();
// Create the SelectCommand.
SqlCommand command = new SqlCommand("SELECT * FROM Customers " +
"WHERE Country = #Country AND City = #City", connection);
// Add the parameters for the SelectCommand.
command.Parameters.Add("#Country", SqlDbType.NVarChar, 15);
command.Parameters.Add("#City", SqlDbType.NVarChar, 15);
adapter.SelectCommand = command;
// Create the InsertCommand.
command = new SqlCommand(
"INSERT INTO Customers (CustomerID, CompanyName) " +
"VALUES (#CustomerID, #CompanyName)", connection);
// Add the parameters for the InsertCommand.
command.Parameters.Add("#CustomerID", SqlDbType.NChar, 5, "CustomerID");
command.Parameters.Add("#CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
adapter.InsertCommand = command;
// Create the UpdateCommand.
command = new SqlCommand(
"UPDATE Customers SET CustomerID = #CustomerID, CompanyName = #CompanyName " +
"WHERE CustomerID = #oldCustomerID", connection);
// Add the parameters for the UpdateCommand.
command.Parameters.Add("#CustomerID", SqlDbType.NChar, 5, "CustomerID");
command.Parameters.Add("#CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
SqlParameter parameter = command.Parameters.Add(
"#oldCustomerID", SqlDbType.NChar, 5, "CustomerID");
parameter.SourceVersion = DataRowVersion.Original;
adapter.UpdateCommand = command;
// Create the DeleteCommand.
command = new SqlCommand(
"DELETE FROM Customers WHERE CustomerID = #CustomerID", connection);
// Add the parameters for the DeleteCommand.
parameter = command.Parameters.Add(
"#CustomerID", SqlDbType.NChar, 5, "CustomerID");
parameter.SourceVersion = DataRowVersion.Original;
adapter.DeleteCommand = command;
return adapter;
}
What actually worked for me from Steve and Hamlet's suggestions is the following. I had one hiccup because I tried to do an accept changes on my rows and table before doing the view adapter update. The accept changes in only needed to save the changes to the datatable before reusing the datatable for displaying in a gridview or other operations.
SqlDataAdapter viewAdapter = new SqlDataAdapter("Select * From Users", DBConn);
SqlCommandBuilder builder = new SqlCommandBuilder(viewAdapter);
viewAdapter.UpdateCommand = builder.GetUpdateCommand();
DataTable Users = new DataTable();
viewAdapter.Fill(Users);
foreach (DataRow user in Users.Rows)
{
foreach (DataColumn c in Users.Columns)
{
Console.WriteLine(c.ColumnName);
if (c.DataType != typeof(DateTime))
{
// Clean up empty space around field entries
user[c.ColumnName] = user[c.ColumnName].ToString().Trim();
}
}
// user.AcceptChanges();
// Do not do an accept changes for either the table or the row before your ViewAdapter Update.
// It will appear as though you do not have changes to push.
}
// Users.AcceptChanges();
viewAdapter.Update(Users);

Adding more number of parameters to sqlparameter class

I have to call a stored procedure but i am having more number of parameters is there any simple way to do this? or simply adding every parameter to sqlparameter class?? like below
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
Be aware that Paramters.Add has an overload that takes in a string and a DbType, so you don't have to call the Parameter constructor. You could replace the line you are currently using to add a new parameter:
command.Parameters.Add(new SqlParameter("#Firstname", SqlDbType.NVarChar)).Value = TextBox1.Text;
with the following shorter (but functionally equivalent) line:
command.Parameters.Add("#Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
If you want to add more parameters, you would simply add them to the Parameters property of your command, like so:
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
command.Parameters.Add("#Lastname", SqlDbType.NVarChar).Value = TextBox2.Text;
Aside from that, have you tried using Parameters.AddWithValue? You can use this if the data type of your column maps to the type of your value in C#. You can find a mapping of C# to SQL Server data typse here.
You would use it like so:
// Assume your sproc has a parameter named #Age that is a SqlInt32 type
int age = 5;
// Since age is a C# int (Int32), AddWithValue will automatically set
// the DbType of our new paramter to SqlInt32.
command.Parameters.AddWithValue("#Age", 5);
If you need to specify the SqlDbType, AddWithValue returns the parameter you just added, so it's as simple as adding an extra statement to set the DbType property at the end, although at this point, you're better off just using the original .Add function and setting the value.
command.Parameters.AddWithValue("#Firstname", TextBox1.Text).DbType = SqlDbType.NVarChar;
Use Array of type SqlParameter and insert that into SqlCommand
SqlCommand Comm = new SqlCommand("Command text", new SqlConnection("Connection String");
SqlParameter[] param = {new SqlParameter("#Name","Value"),
new SqlParameter("#Name","Value"),
........
};
Comm.Parameters.AddRange(param);
Just call the command.Parameters.Add method multiple times:
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Firstname", SqlDbType.NVarChar, 100).Value = TextBox1.Text;
command.Parameters.Add("#Lastname", SqlDbType.NVarChar, 100).Value = TextBox2.Text;
command.Parameters.Add("#City", SqlDbType.NVarChar, 100).Value = TextBox3.Text;
command.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(TextBox4.Text);
....... and so on .....
You may use like it
return new SqlParameter[]
{
new SqlParameter("#Firstname", SqlDbType.VarChar)
{
Value = Firstname.Text
},
new SqlParameter("#Lastname", SqlDbType.VarChar)
{
Value = Lastname.Text
},
};
You can use dapper-dot-net
sample code:
var dog = connection.Query<Dog>("select Age = #Age, Id = #Id", new { Age = (int?)null, Id = guid });
Insert example:
connection.Execute(#"insert MyTable(colA, colB) values (#a, #b)",
new[] { new { a=1, b=1 }, new { a=2, b=2 }, new { a=3, b=3 } }
).IsEqualTo(3); // 3 rows inserted: "1,1", "2,2" and "3,3"
The command.Parameters.Add is deprecated. Rather use command.Parameters.AddWithValue .
For this, you would call it many times for each parameter.
// Mention size of the nvarchar column , here i give 500 , you can use its length for #Firstname as you mention in database according to your database
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Firstname", SqlDbType.NVarChar,500).Value = TextBox1.Text;

Categories

Resources