Confused About How to insert xml value into database - asp.net

I am dealing with xml files and I have found an example here.I have changed connection string and created a table named MyProducts then I have manually located my Product.xml files inside App_Data folder.When i run my program get this execption
Invalid object name 'Product'.
So in the debug mode I have noticed that myxml variable is null What am i doing wrong
protected void Button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command ;
SqlDataAdapter adpter = new SqlDataAdapter();
DataSet ds = new DataSet();
XmlReader xmlFile ;
string sql = null;
int product_ID = 0;
string Product_Name = null;
double product_Price = 0;
connetionString = "Data Source=.\\sqlexpress;Initial Catalog=Northwind;Integrated Security=sspi";
connection = new SqlConnection(connetionString);
xmlFile = XmlReader.Create(Server.MapPath("~/App_Data/Product.xml"), new XmlReaderSettings());
ds.ReadXml(xmlFile);
int i = 0;
connection.Open();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
product_ID = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[0]);
Product_Name = ds.Tables[0].Rows[i].ItemArray[1].ToString();
product_Price = Convert.ToDouble(ds.Tables[0].Rows[i].ItemArray[2]);
sql = "insert into Product values(" + product_ID + ",'" + Product_Name + "'," + product_Price + ")";
command = new SqlCommand(sql, connection);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
}
connection.Close();
Label1.Text = "ok";
}

As I've said in comments, you've just misspelled your table name - you table called MyProducts and you're trying to insert into Product
insert into MyProducts ...

Related

Using datareader to count Asp.net

I'm checking if a barcode from a database table(using a select query) exists and insert the details into another database table else the barcode does not exist. The inserts fine but I would like to count the number of barcodes entered. Say within a session an user enters 5 barcodes then the total count is 5 but my code keeps returning 1 and not incrementing.
protected void btnReturn_Click(object sender, EventArgs e)
{
string barcode = txtBarcode.Text;
string location = lblLocation.Text;
string user = lblUsername.Text;
string actType = lblAct.Text;
string date = lblDate.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString());
//commands identifying the stored procedure
SqlCommand cmd = new SqlCommand("selectCrate", conn);
SqlCommand cmd1 = new SqlCommand("CreateCrateBox", con);
// execute the stored procedures
cmd.CommandType = CommandType.StoredProcedure;
cmd1.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#crateno", barcode);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows) {
while (reader.Read())
{
lblResult.Text = reader[0].ToString();
lblResult1.Text = reader[1].ToString();
cmd1.Parameters.Add("#crateno", SqlDbType.NVarChar).Value = barcode);
cmd1.Parameters.Add("#CurrentLocation", SqlDbType.NVarChar).Value = location;
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
cmd1.Parameters.Add("#status", SqlDbType.NVarChar).Value = actType;
counter = counter + 1;
}
reader.Close();
cmd1.ExecuteNonQuery();
txtCount.Text = counter.ToString();
lblCount.Text = string.Format("Number of rows: {0}", counter);
}
else
{
lblError.Text = barcode + " does not exist!!";
}
}
You can store the number in session then do something with it when the session ends (store it in a database or whatever you want). Declare a session variable:
Session[“NumInserts”] = 0;
Then update it with each insert:
Session[“NumInserts”] = (int) Session[“NumInserts”] + 1;
That variable will be maintained as long as the session exists. Also, make sure you only declare the session variable once and don’t ever allow it to reset during the session’s life cycle. Otherwise, it will go back to 0 and give you inaccurate results.
i rechecked to make sure and i misunderstood your question which led to some confusion.
And to answer your question i don't think there is any easy solution to update realtime the numbers. Any solution of i can think of is websocket connection which I personally have no knowledge of inside webforms(Don't even know if its possible).
I formatted your code. This should give you the total rows back in one go(no realtime update on screen).
protected void btnReturn_Click(object sender, EventArgs e)
{
int counter = 0;
string barcode = txtBarcode.Text;
string location = lblLocation.Text;
string user = lblUsername.Text;
string actType = lblAct.Text;
string date = lblDate.Text;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString()))
{
con.Open();
//commands identifying the stored procedure
using (SqlCommand cmd = new SqlCommand("selectCrate", con))
{
using (SqlCommand cmd1 = new SqlCommand("CreateCrateBox", con))
{
// execute the stored procedures
cmd.CommandType = CommandType.StoredProcedure;
cmd1.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#crateno", barcode));
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
lblResult.Text = reader[0].ToString();
lblResult1.Text = reader[1].ToString();
cmd1.Parameters.Add("#crateno", SqlDbType.NVarChar).Value = barcode;
cmd1.Parameters.Add("#CurrentLocation", SqlDbType.NVarChar).Value = location;
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
cmd1.Parameters.Add("#status", SqlDbType.NVarChar).Value = actType;
counter++;
}
cmd1.ExecuteNonQuery();
txtCount.Text = counter.ToString();
lblCount.Text = string.Format("Number of rows: {0}", counter);
}
else
{
lblError.Text = barcode + " does not exist!!";
}
}
}
}
}
}

how to retrieve multiple data from database using SqlDataReader?

i have database table in which i have two columns name picid and pic1..in my pic1 column i have three data..now while wanting to retrive the data using sqldatareader i am getting the top of the column data..how to get the all data of that column and use it for the further purpose..
my code
protected void Page_Load(object sender, EventArgs e)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From pictable", objsqlconn);
SqlDataReader grpIDreader = cmd.ExecuteReader();
grpIDreader.Read();
string path = grpIDreader["pic1"].ToString();
//slide.Attributes["style"] = String.Format("background-image:url('{0}')", path);
image1.Attributes["src"] = String.Format("{0}", path);
image2.Attributes["src"] = String.Format("{1}", path);
image3.Attributes["src"] = String.Format("{2}", path);
}
i want to just get the path which are saved in the pic1 column of the database..
i am getting this error " System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list."
i have tried like that also and getting same error
protected void Page_Load(object sender, EventArgs e)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From pictable", objsqlconn);
SqlDataReader grpIDreader = cmd.ExecuteReader();
string[] path={"","",""};
int i = 0;
while(grpIDreader.Read())
{
path[i++] = grpIDreader["pic1"].ToString();
}
//slide.Attributes["style"] = String.Format("background-image:url('{0}')", path);
image1.Attributes["src"] = String.Format("{0}", path[0]);
image2.Attributes["src"] = String.Format("{1}", path[1]);
image3.Attributes["src"] = String.Format("{2}", path[2]);
}
You are getting a string formatting error, not a database error:
image1.Attributes["src"] = String.Format("{0}", path); //This works, as 0 indicates the first argument you are passing in
image2.Attributes["src"] = String.Format("{1}", path); //This won't work, as you are asking for the second argument, which doesn't exist
Use the following to get each row
using (SqlDataReader grpIDreader = cmd.ExecuteReader())
{
while (grpIDreader.Read()) //.Read() advances to the next row and returns false if there are no more
{
string path = grpIDreader["pic1"].ToString();
//other stuff here
}
}
also
instead of this
image1.Attributes["src"] = String.Format("{0}", path[0]);
do this
image1.Attributes["src"] = path[0];

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack when I use scope identity

Here is ehat I try to do
on button_click I read the values from the text boxes and insert them in them in the database.
as tourist number for example maybe two or three tourists with ExecuteScalar; i get the ids of teh tourists which are inserted!
public void cmdInsert_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
string numtourist = (string)Session["tourist_number"];
for (int i = 0; i < Int32.Parse(numtourist); i++)
{
TextBox tx888 = (TextBox)FindControl("txtNameK" + i.ToString());
TextBox tx888_1 = (TextBox)FindControl("txtMidNameK" + i.ToString());
TextBox tx888_2 = (TextBox)FindControl("txtLastNameK" + i.ToString());
string insertSQL = "INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)";
insertSQL += " VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir) SELECT ##IDENTITY";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#Excursion_ID", Convert.ToInt32(mynew2));
cmd.Parameters.AddWithValue("#Excursion_date_ID", Convert.ToInt32(mynewnewstring));
cmd.Parameters.AddWithValue("#Name_kir", tx888.Text);
cmd.Parameters.AddWithValue("#MidName_kir", tx888_1.Text);
cmd.Parameters.AddWithValue("#LastName_kir", tx888_2.Text);
int added;
try
{
con.Open();
added = (int)cmd.ExecuteScalar();
lblproba.Text = "";
Tourist.Add(added);
lblproba.Text += Tourist.Count();
}
catch (Exception ex)
{
lblproba.Text += ex.Message;
}
finally
{
con.Close();
}
}
createReservation();
}
}
I call CreateReservationFunction AND i CREATE A NEW RESERVAION WITH THE ID OF THE USER WHO HAS MADE THE RESERVATION. wITH SELECT IDENTITY I TRY TO GET THE RESERVATION_ID of the reservation and here I get the exception "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack". So I wonder can this exception has something commn with the fact that in my solution exceptthe asp.net web projectI got library class in which I has .edmx file The entity framework model of my database and in my last form I don't use Ado,net but Entity framework
public void createReservation()
{
string insertSQL = "Insert INTO RESERVATIONS (User_ID) values (#User_ID) SELECT ##IDENTITY";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#User_ID", 9);
try
{
con.Open();
string added = cmd.ExecuteScalar().ToString();
createTouristReservation(added);
}
catch (Exception ex)
{
lblproba.Text+= ex.Message;
}
}
Don't use ##IDENTITY but SCOPE_IDENTITY and add a semicolon between the insert and the select.
string insertSQL = #"INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)
VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir)
;SELECT CAST(scope_identity() AS int)";

How to update sql database table info with excel file using file uploaded

I am trying to update the files in the table that I have created. I am using file uploader to insert my Excel file and upload it to the database. But currently my code creates a new database table each time a file is uploaded, which I don't want it to do. I want to just update/replace the whole file in database table. How do I do this?
This is my code:
private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["nConnectionString2"].ConnectionString;
}
private void CreateDatabaseTable(DataTable dt, string tableName)
{
string sqlQuery = string.Empty;
string sqlDBType = string.Empty;
string dataType = string.Empty;
int maxLength = 0;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName));
for (int i = 0; i < dt.Columns.Count; i++)
{
dataType = dt.Columns[i].DataType.ToString();
if (dataType == "System.Int32")
{
sqlDBType = "INT";
}
else if (dataType == "System.String")
{
sqlDBType = "NVARCHAR";
maxLength = dt.Columns[i].MaxLength;
}
if (maxLength > 0)
{
sb.AppendFormat(string.Format(" {0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength));
}
else
{
sb.AppendFormat(string.Format(" {0} {1}, ", dt.Columns[i].ColumnName, sqlDBType));
}
}
sqlQuery = sb.ToString();
sqlQuery = sqlQuery.Trim().TrimEnd(',');
sqlQuery = sqlQuery + " )";
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter)
{
string sqlQuery = string.Empty;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName));
sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath));
sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter));
sqlQuery = sb.ToString();
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName);
if (fileInfo.Name.Contains(".csv"))
{
string fileName = fileInfo.Name.Replace(".csv", "").ToString();
string csvFilePath = Server.MapPath("UploadExcelFile") + "\\" + fileInfo.Name;
//Save the CSV file in the Server inside 'MyCSVFolder'
FileUpload1.SaveAs(csvFilePath);
//Fetch the location of CSV file
string filePath = Server.MapPath("UploadExcelFile") + "\\";
string strSql = "SELECT * FROM [" + fileInfo.Name + "]";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'";
// load the data from CSV to DataTable
OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString);
DataTable dtCSV = new DataTable();
DataTable dtSchema = new DataTable();
adapter.FillSchema(dtCSV, SchemaType.Mapped);
adapter.Fill(dtCSV);
if (dtCSV.Rows.Count > 0)
{
CreateDatabaseTable(dtCSV, fileName);
Label1.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName);
string fileFullPath = filePath + fileInfo.Name;
LoadDataToDatabase(fileName, fileFullPath, ",");
Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName);
}
else
{
Label1.Text = "File is empty.";
}
}
else
{
Label1.Text = "Unable to recognize file.";
}
}
}
The code that creates the tables should give an error when you run it if the tables already exists as you never drop them.
That said, one solution might be to add a check to see if the table already exists in the code that creates a new table; it should be something like:
IF OBJECT_ID('TABLE', 'U') IS NULLwhere TABLEit the name of the table that you want to add, so the code might look like:
sb.AppendFormat(string.Format("IF OBJECT_ID({0}, 'U') IS NULL CREATE TABLE {0} (", tableName));
Another, possibly better, option would be to run a query to check if the table exists before you run the CreateDatabaseTable(dtCSV, fileName);statement. You can do the check by executing something like IF OBJECT_ID('tableName', 'U') IS NULL SELECT 1 ELSE SELECT 0 (this would return 1 if the table doesn't exist), and then conditionally execute the CreateDatabaseTablestatement.

ASP.Net insert data from form to a database Exception

I'm trying to insert data from a form to my database and it is throwing this error:
No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.
Maybe it has to do with the fact that I try to get a data from a dropdownlist and I'm not really sure the syntax is great.
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
conn.Open();
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", Title);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", GenreDropDown);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", Descreption);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
You -weren't using any of the vars where you had the values
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", titlename);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", genre);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", descp);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
The problem is that you are trying to use the entire textbox as the value to the parameter.
Change:
cmd.Parameters.AddWithValue("Title", Title);
to
cmd.Parameters.AddWithValue("Title", Title.Text);

Resources