I am trying to insert some fields into the local ms access database using webmethod(services) and website. I have tried looking up but cannot seem to spot where I've gone wrong. Can anyone tell me if I am doing it right. The code below does not add new data into the database nor does it direct me back to the page requested.
Services Webmethod:
[WebMethod]
public void AddNewPosts(string postUserName, string postTitle, DateTime postMessagepostDateTime, int subTopicId, string postMessage)
{
//Connection string for the datbase
string database = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Forum.accdb;Persist Security Info=True";
OleDbConnection myConn = new OleDbConnection(database);
//Execute the query
string queryStr = "Insert into Posts (TopicId, PostTitle, PostUserName, PostDateTime) VALUES (" + subTopicId + ",'" + postTitle + "','" + postUserName + "'," + postMessagepostDateTime + ")";
// Create a command object
OleDbCommand myCommand = new OleDbCommand(queryStr, myConn);
// Open the connection
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
Calling the above method from my website:
protected void btnSubmit_Click(object sender, EventArgs e)
{
//string postUserName = Page.User.Identity.Name;
string postUserName = "tom123";
string postTitle = txtTitle.Text;
string postMessage = txtMessage.Text;
DateTime postDateTime = DateTime.Now;
int subTopicId = int.Parse(Request.QueryString["id"]);
Service fs = new Service();
fs.AddNewPosts(postUserName, postTitle, postDateTime, subTopicId, postMessage);
//Redirect back to the SubTopic page
Response.Redirect("SubTopic.aspx?id=" + subTopicId.ToString());
}
Can you try with quotes around the date time
string queryStr = "Insert into Posts (TopicId, PostTitle, PostUserName, PostDateTime) VALUES (" + subTopicId + ",'" + postTitle + "','" + postUserName + "','" + postMessagepostDateTime + "')";
Related
I have a form that users will fill out and when they submit, all data is pushed to a database.
My Problem is that I have a CheckBoxList and if a user selects multiple checkboxes it only inputs the first item into the database. How do I make it so that all the items are inputted into the same row and separated by commas.
Here is my current code:
protected void Button1_Click(object sender, EventArgs e)
{
//Start Code
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = conString + txtFirst.Text + "','" + txtLast.Text +
"','" + txtEmail.Text + "','" + lstBranch.Text + "','" + lstAccess.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
}
You can loop the items like this
string result = string.Empty;
for (int i = 0; i < checkboxlist1.Items.Count; i++)
{
if (checkboxlist1.Items[i].Selected)
{
result += checkboxlist1.Items[i].Text + ", ";
}
}
// remove the final comma.
// add 'result' to your sql stmt.
So what I'm trying to do is once I click a button. I want one sql query to insert values to the "Return_Process" Table and another sql query to delete data from the matching loan ID in another table, which is "Loan_Process".
This is the code I have written but its not deleting anything, its inserting the values to the return process but not deleting it from the loan process.
//Global variable declaration
string path;
string sql;
string sql2;
//create a method for database connection
public void connection()
{
//connection string
path = #"Data Source=NATHAN-PC\SQLEXPRESS;Initial Catalog=ASP;Integrated Security=True";
}
protected void Button1_Click(object sender, EventArgs e)
{
{
connection();
SqlConnection con = new SqlConnection(path);
con.Open();
//try
{
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID) VALUES ('" + txtRID.Text + "','" + txtfine.Text + "','" + TextBox1.Text + "','" + txtLID.Text + "')";
sql2 = "Delete FROM Loan_Process WHERE Loan_ID='"+txtLID+"'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
//lblerrormsg.Visible = true;
//lblerrormsg.Text = "Success";
con.Close();
//GridView1.DataBind();
}
//catch (SqlException)
//{
// //lblerrormsg.Visible = true;
// //lblerrormsg.Text = "Invalid";
//}
con.Close();
//GridView1.DataBind();
}
}
}
}
I'm pretty bad at ASP.net, so if someone could tell me what to do to execute both queries at the same time, would greatly appreciate it.
Do something like this:
//your code
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID)"
+ " VALUES (#rid, #fine, #retDate, #lid); " //note ; inside
+ "Delete FROM Loan_Process WHERE Loan_ID=#lid;";
var cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#rid", SqlDbType.Int).Value = Int.Parse(txtRID.Text);
//similar for 3 remaining parameters. Just set correct SqlDbType
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Button Click Code
String cs = null;
SqlConnection scon = null;
SqlCommand cmd = null;
private void btnOk_Click(object sender,EventArgs e)
{
String name = txtBoxName.Text.ToString();
String mobile = txtBoxMobile.Text.ToString();
String address = txtBoxAddress.Text.ToString();
String ty = null;
if (radioButtonCow.Checked)
{
ty = radioButtonCow.Text.ToString();
}
else {
ty = radioButtonBuffalo.Text.ToString();
}
int n = 0;
using(scon = new SqlConnection(cs)){
scon.Open();
String query = "insert into new_customer(name,mobile,address,type)
values('" + name + "','" + mobile + "','" + address + "','" + ty + "')";
cmd = new SqlCommand(query, scon);
n = cmd.ExecuteNonQuery();
}
}
private void NewCustomer_Load(object sender, EventArgs e)
{
cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
}
}
When I run this application it runs successfully without showing any error but it doesn't insert any records in the table. The table has the fields id, name, mobile, address and type. id is a primary key and it's an identity field. All the other fields are of varchar type.
Why doesn't it insert data in the table?
You just pass your parameters in this way as i mentioned below,
SqlConnection scon = new SqlConnection(cs);
scon.Open();
String query = "insert into new_customer values(#name,#mobile,#address,#type)";
cmd = new SqlCommand(query, scon);
cmd.Parameters.AddWithValue("#name",name);
cmd.Parameters.AddWithValue("#name",mobile);
cmd.Parameters.AddWithValue("#name",address);
cmd.Parameters.AddWithValue("#name",ty);
cmd.ExecuteNonQuery();
scon.Close();
try by wrap the type field as [type]
String query = "insert into new_customer(name,mobile,address,[type]) values('" + name + "','" + mobile + "','" + address + "','" + ty + "')";
I am creating an Shopping website as my project in asp.net but the problem am facing is that when a user clicks on confirm order button then data is not getting inserted in the database. To be more clear, This is working when i use the User created directly in the table but when i use the User created using registration form then its not working(i can login with this user id as data is inserted in the table). Also its not even providing any error message and is just redirecting to invoice page as i coded but without inserting data into the table.....Strange error i can ever imagine any help will be appreciated. Waiting for your reply. Thank You
this one i think maybe creating problem
ArrayList ar = new ArrayList();
ArrayList ar1 = new ArrayList();
ArrayList ar2 = new ArrayList();
ArrayList ar3 = new ArrayList();
SqlCommand command = new SqlCommand("Select Product_id,Product_name,Product_cost,Quantity from Cart where User_id='" + userid + "'",con);
try
{
con.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int a = Convert.ToInt32(reader[0]);
ar.Add(a);
String pdname = reader[1].ToString();
ar1.Add(pdname);
int pcost = Convert.ToInt32(reader[2]);
ar2.Add(pcost);
int q = Convert.ToInt32(reader[3]);
ar3.Add(q);
}
pkid = (int[]) ar.ToArray(typeof(int));
pkname = (String[]) ar1.ToArray(typeof(String));
pkcost = (int[]) ar2.ToArray(typeof(int));
pkq = (int[]) ar3.ToArray(typeof(int));
con.Close();
}
catch (Exception ex)
{
Response.Write("Error at second" + ex);
}
try
{
con.Open();
for (int i = total-1; i>=0; i--)
{
SqlCommand smd = new SqlCommand("Insert into Orders values('"+orderid+"','" + userid + "','" + name + "','" + pkid[i] + "','" + pkname[i] + "','" + address + "','" + pkq[i] + "','" + pkcost[i] + "','" + date + "','" + payment.SelectedItem.ToString() + "','Pending')", con);
smd.ExecuteNonQuery();
}
con.Close();
}
Ok so my probelm is solve. The solution for this was that i just remove try catch block and thats it its working as expected. Anyways i don't know yet what its not working using try catch block.
I'm trying to duplicate a record in my database and I used this code you see below, the sql query worked perfectly in sql server but here I don't know what the problem...help me please
//Insert new Order
int newOrderId = 0;
if (e.CommandName == "Repeat")
{
try
{
SqlConnection con = DataAccess.Connection.GetDBConnection();
//duplicate the jobs from the old order to the new added order
sqlCmd.Parameters.Clear();
string com2 = "Insert Into [OrderItems] (orderId, productId, quantity, [length], note, multipleSlip, internalDiameter, " +
"wall, machineReCuttingId,winderId, jobNote) (select #newOrderId, productId, quantity, [length], note, multipleSlip, " +
"internalDiameter, wall, machineReCuttingId, winderId, jobNote FROM OrderItems Where orderId=#oldOrderId)";
SqlCommand sqlCmd = new SqlCommand(com2, con);
sqlCmd.Parameters.Add("#newOrderId", SqlDbType.Int).Value = newOrderId;
//assign the old order Id to the insert parameter #oldOrderId
sqlCmd.Parameters.Add("#oldOrderId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument);
sqlCmd.ExecuteNonQuery();
StatusLabel.Text = "The New Order is" + newOrderId.ToString() + " The Old order ID is: " + e.CommandArgument.ToString();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
OrderGridView.DataSource = ViewDataSource(selectCustomer);
OrderGridView.DataBind();
// Response.Redirect("../Orders/AddNewOrder.aspx?customerId=" + selectCustomer + "&" + "orderId=" + newOrderId);
}
By the way I tested the values of newOrderId and the oldOrderId they are both correct