select , update Query c# error - c#

I am importing excel file into sql database.Working code I am Using is:
public static void ImportToSql(string excelfilepath)
{
string ssqltable = "Inventory";
string myexceldataquery = "select LocalSKU,QOH from [sheet1$]";
try
{
string sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" + excelfilepath + "; Extended Properties=\"Excel 12.0; HDR=Yes; IMEX=2\"";
string ssqlconnectionstring = "Data Source=DELL\\SQLSERVER1;Trusted_Connection=True;DATABASE=CAMO;CONNECTION RESET=FALSE";
//execute a query to erase any previous data from our destination table
string sclearsql = "delete " + ssqltable;
enter code here
"HERE I DON'T WANT THIS STEP TO DELETE TABLE DATA AND THEN INSERTING IT.INSTEAD I WANT TO UPDATE TABLE DATA"
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
while (dr.Read())
{
//bulkcopy.WriteToServer(dr);
}
Console.WriteLine(".xlsx file imported succssessfully into database.", bulkcopy.NotifyAfter);
oledbconn.Close();
}
I don't know how to update it that's why what I do is I delete data and then insert. Please help me with Updating columns QOH based on primarykey table LocalSKU.
I tried the following thing but it gives error saying "Merge statement must be terminated by a semi-column(;)"
SqlCommand sqlcmd = new SqlCommand(#"MERGE Inventory AS target
USING (select LocalSKU, QOH from #source) as source
ON (source.ID = target.ID)
WHEN MATCHED THEN
UPDATE SET QOH = source.QOH
WHEN NOT MATCHED THEN
INSERT (LocalSKU, QOH )
VALUES (source.LocalSKU, source.QOH )", sqlconn);
SqlParameter param=new SqlParameter();
sqlcmd.Parameters.AddWithValue("#source", ssqltable);
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "dbo.tStudent";

Basically I want only two columns KitSKU and Quantity out of many
columns in table Kits.
Change:
SqlDataAdapter da = new SqlDataAdapter("select * from [KitSKU] , [Quantity] from Kits", sqlCon);
To:
SqlDataAdapter da = new SqlDataAdapter("select [KitSKU] ,[Quantity] from Kits", sqlCon);
you want to select column: [KitSKU] and [Quantity] from table: Kits
Thanks Max.. also If I want to Update it rather than inserting, how to
implement that.
Use following code, for updating KitSKU and Quantity:
SqlDataAdapter da = new SqlDataAdapter("update Kits set [KitSKU] = 'entersku' ,[Quantity] = 5 where [KutSKU] = 'what record it should update'", sqlCon);
But I wouldn't recommend that code, since it isn't parameterized and I think you should try with some basic sql lessons and using sql parameters.

Related

How to select data and store the result in a variable

I am trying to select data from MS database and store the result in a variable.
I want to use default visual studio commands without a framework.
Firstly I am doing an insert statement, then i want to retrieve the scope_identity().
SqlCommand recipe_insert_command = new SqlCommand("INSERT INTO RecipeTbl (USER_ID,RECIPE_DESC) VALUES ('" + user_id + "','" + recipe_desc + "');", con);
recipe_insert_command.ExecuteNonQuery();
SqlCommand getRecipeID_command = new SqlCommand("SELECT SCOPE_IDENTITY();", con);
getRecipeID_command.ExecuteNonQuery();
The insert works. What about the select?
Maybe i suggest to display to datagridview like this. Sorry for writing in MySQL but it is almost similar to SQL.
string conn = "datasource=localhost;port=3306;username=root;password=;CharSet=utf8mb4;";
string query = "SELECT * FROM RecipeTbl;"
MySqlConnection connection = new MySqlConnection(conn);
MySqlDataAdapter adapter = new MySqlDataAdapter(query, connection);
DataSet ds = new DataSet();
adapter.Fill(ds, "RecipeTbl");
datagridview1.DataSource = ds.Tables["RecipeTbl"];
Beware of sql injections.
Use parameterized queries.
Always free the resources used: using statement.
string sql =
"INSERT INTO RecipeTbl (USER_ID, RECIPE_DESC) VALUES (#user_id, #recipe_desc);" +
"SELECT SCOPE_IDENTITY();";
using (var con = new SqlConnection(connectionString))
using (var recipeCommand = new SqlCommand(sql, con))
{
con.Open();
recipeCommand.Parameters.Add("user_id", SqlDbType.Int).Value = user_id;
recipeCommand.Parameters.Add("recipe_desc", SqlDbType.NVarChar).Value = recipe_desc;
var id = (decimal)recipeCommand.ExecuteScalar();
Console.WriteLine(id);
}
Of course, specify the data types that are used in your table: SqlDbType.

How to make insert operation using MySqlDataAdapter in ASP.NET

I am able to perform insert using the code which I've made comments here. How to achieve the same using MySqlDataAdapter ? The code I've written isn't working.
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
MySqlDataAdapter da = new MySqlDataAdapter("insert into tblStudent (StudentId, StudentName) values ('" + sid.ToString() + "', '" + sname.ToString() + "')", con);
// con.Open();
// MySqlCommand cmd = con.CreateCommand();
// cmd.CommandType = CommandType.Text;
// cmd.CommandText = "insert into tblStudent (StudentId, StudentName) values('" + sid.ToString() + "', '" + sname.ToString() + "')";
// cmd.ExecuteNonQuery();
// con.Close();
Help with suggestions.
To insert a single record you could simply use the MySqlCommand instead of a MySqlDataAdapter. MySqlDataAdapter has many functionality and allows you to execute Insert, Update and Delete actions on your data but you first need to reach the server to fill a DataTable, then add a new record to the datatable and finally call Update. Not worth the effort if you just need to insert a single record
However if you really want to try to use an DataAdapter then you need this code
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
string selectText = "SELECT studentID, StudentName FROM tblStudent WHERE 1=0";
using(MySqlDataAdapter da = new MySqlDataAdapter(selectText, con))
{
MySqlCommandBuilder bd = new MySqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
// This is important, because Update will work only on rows
// present in the DataTable whose RowState is Added, Modified or Deleted
dt.Rows.Add(sid, sname);
da.Update(dt);
}

Display database values in textbox

I have a datatable with 2 columns, ID and Name, I have populated my combobox with the column ID.
string Query = "SELECT * FROM [Database]";
OleDbConnection me = new OleDbConnection(connection);
OleDbCommand constr = new OleDbCommand(Query, me);
me.Open();
OleDbDataReader reader = constr.ExecuteReader();
while(reader.Read())
{
textBox15.Text = (reader["Name"].ToString());
}
reader.Close();
When I select an item from the combobox, I want to retrieve values from the Column Name in the same row. For instance I select a value from my combobox which is in datarow 1 and it matches the datarow 1 in the table Name
Is there anyway to do this?
I am currently here
{
string Query = "SELECT * FROM [Database] where Name ='" + comboBox6.Text + "' "; string y = textBox15.Text
OleDbConnection me = new OleDbConnection(connection);
OleDbCommand constr = new OleDbCommand(Query, me);
me.Open();
OleDbDataReader reader = constr.ExecuteReader();
constr.Parameters.Add(new OleDbParameter("#Name", y));
while (reader.Read())
{
textBox15.Text = reader["Name"].ToString();
}
me.Close();
}
}
I am still getting an error "No parameters given for one or more values" I am sure that the code is right.
You'll need to add a parameter to your SQL query. For example:
string myName = myComboBox.SelectedItem.Text;
string Query = "SELECT * FROM [Database] WHERE Name = ?";
OleDbConnection conn = new OleDbConnection(connection);
OleDbCommand cmd = new OleDbCommand(Query, conn);
cmd.Parameters.Add(new OleDbParameter("#name", myName));
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while(reader.Read())
etc...
I'm not sure of the exact syntax for the OLE DB .NET Provider, but hopefully this helps somewhat.

Having some trouble using scope identity

I have two tables, one containing names, and one containing rates and other data that is lined to each name. After I insert a new name into table A, I want to get the newly auto generated PK to now use to insert into my other table B with rates.
How can I do this? I read about scope_identity online but I'm not sure how to use it.
This is what I have so far:
SqlConnection con = new SqlConnection(pubvar.x);
SqlCommand command = con.CreateCommand();
command.CommandText ="Insert into A values('" +Name + "')";
SqlCommand command2 = con.CreateCommand();
command2.CommandText = "Insert into B values(....)";
SELECT SCOPE_IDENTITY();
con.Open();
command.ExecuteNonQuery();
con.Close();
Considering the case you've described, I don't see any need to return the identity from the database. You can simply issue both statements in one command:
using (var cnx = new SqlConnection(pubvar.x))
using (var cmd = new SqlCommand
{
Connection = cnx,
CommandText = #"
insert into A (Name) values (#name)
insert into B (A_ID, Rate) values (scope_identity(), #rate)
",
Parameters =
{
new SqlParameter("#name", name),
new SqlParameter("#rate", .5m) //sample rate
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}

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

Categories

Resources