This is html form; I want to insert value from this form to my SQL Server table using C#. I try to add, but I do not know how to make correct connection and how to use data from this simple form to add it to database. I am using Microsoft SQL Server Management Studio and I have real database and server
<form id="form1" runat="server">
<h1> Find and search about any employee in Faten</h1>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<input id="ID" type="text" />
<input id="name" type="text" />
<input id="lname" type="text" />
<input id="pass" type="text" />
<input id="Submit1" type="submit" value="submit" />
</form>
This is my C# code
protected void Button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO Ruser(ID, Name, Lname, pass) VALUES (#ID, #name, #lanme, #pass);";
SqlConnection connection1 = new SqlConnection();
SqlCommand cmd = new SqlCommand(query, connection1);
cmd.CommandType = CommandType.TableDirect;
cmd.Parameters.AddWithValue("#Id", "33");
cmd.Parameters.AddWithValue("#name", "abc");
cmd.Parameters.AddWithValue("#lanme", "abc");
cmd.Parameters.AddWithValue("#pass", "abc");
connection1.Open();
int result = cmd.ExecuteNonQuery();
// Check Error
if (result < 0)
Console.WriteLine("Error inserting data into database!");
}
you can use this one:
var connStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI";
using(SqlConnection openCon=new SqlConnection(connStr))
{
}
Or:
var connStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Userid=UserName;Password=Secret";
using(SqlConnection openCon=new SqlConnection(connStr))
{
}
But in the better way you sould save your connectionstring in webconfig or if you use .netcore appsetting file and read it from that.
Related
I know that the connection string is not the problem because I can read data from the database fine but I cannot figure out why I cannot insert data into the database.
.aspx file
<div class="column one-second">
<asp:TextBox placeholder="Your name" type="text" name="name" id="namelbl" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one-second">
<asp:TextBox placeholder="location" type="text" name="location" id="LocationLbl" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one">
<asp:TextBox placeholder="Body" type="text" name="text" id="TextLBL" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one">
<asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload>
<asp:Label ID="lblmessage" runat="server" />
</div>
<div class="column one">
<asp:Button id="submit" Text="Submit" runat="server" OnClick="submit_Click"> </asp:Button>
</div>
C# function
protected void submit_Click(object sender, EventArgs e)
{
Console.WriteLine("BUTTON CLICKED");
string constr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO blo(Title, post, location) VALUES (#Title, #post, #location)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
string title = namelbl.Text;
Console.WriteLine(title);
cmd.Parameters.AddWithValue("Title", title);
string post = TextLBL.Text;
cmd.Parameters.AddWithValue("post", post);
string location = LocationLbl.Text;
cmd.Parameters.AddWithValue("location", location);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Your query was not able to work as you mistype the parameter name in your .AddWithValue().
cmd.Parameters.AddWithValue("Title", title);
cmd.Parameters.AddWithValue("post", post);
cmd.Parameters.AddWithValue("location", location);
The correct way should be:
cmd.Parameters.AddWithValue("#Title", title);
cmd.Parameters.AddWithValue("#post", post);
cmd.Parameters.AddWithValue("#location", location);
RECOMMENDATIONS
1. It is recommended not to use `.AddWithValue()` as the concern mentioned in this [article](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/). Please ensure that you need to pass the value with **exact datatype and length** that matches the respective table column in the `SqlParameter`.
cmd.Parameters.Add("#Param", <<MySqlDbType>>, <<Length>>).Value = value;
As you apply using block for MySqlConnection, MySqlCommand, you don't have to manually call con.Close() as these IDisposable objects will dispose the resources & connection automatically as mentioned in this article.
(Optional) Add try catch block and get value from ExecuteNonQuery() for verifying the record is inserted into the database and exception handling.
Exception handling will be useful in debugging and handling the exception hit during the execution. At the same time, you can provide a meaningful error message to notify the users.
ExecuteNonQuery() able to return the value indicate
The number of rows affected.
Hence, this will also be useful to return a useful message to notify whether the record is successfully inserted/updated into the database or not.
In the end, your code should be:
try
{
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO blo(Title, post, location) VALUES (#Title, #Post, #Location)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
string title = namelbl.Text;
Console.WriteLine(title);
cmd.Parameters.AddWithValue("#Title", title);
string post = TextLBL.Text;
cmd.Parameters.AddWithValue("#Post", post);
string location = LocationLbl.Text;
cmd.Parameters.AddWithValue("#Location", location);
con.Open();
var recordAffected = (int)cmd.ExecuteNonQuery();
if (recordAffected > 0)
{
// Record successfully inserted case
}
else
{
// Record fail inserted case
}
}
}
}
catch (Exception ex)
{
// Handling exception
}
Edited:
Much appreciated and credited to the comment provided by #BradleyGrainger, I had 'strikethrough' recommendation 1 as the concerns mentioned in Can We Stop Using .AddWithValue() are handled by MySql.
Start Using AddWithValue
The primary reason that AddWithValue is OK to use is that MySQL’s text protocol is not typed in a way that matters for client-side type inference.
I am getting an error with my insert command. I am trying to add the users input data from the text boxes on the html page into the access database I already have created and connected. I am just having a problem with the syntax of my insert command.
This is my HTML page
<form name="insert" method="post" action="insertinventory.aspx">
<center>
<h1> FLOATEEZ Add Inventory </h1>
Item Number: <input type="text" name="txtnum"> <br>
Item Name: <input type="text" name="txtname"> <br>
Item Description: <input type="text" name="txtdescription"> <br>
Item Price: <input type="text" name="txtprice"> <br>
Item Quantity on Hand: <input type="text" name="txtqoh"> <br>
Item Picture: (text only) <input type="text" name="txtpicture"> <br><br>
<input type="submit" value="Submit">     <input type="reset">
</center>
</form>
This is my aspx page minus my database information
<%# Page Language="C#" Debug="true" %>
<%# Import Namespace="System.Data.Odbc" %>
<%
Response.Write("<html><head><title>Insert into Inventory </title></head></body>");
Response.Write("<body bgcolor=lightblue>");
OdbcConnection myconn;
OdbcCommand mycmd;
OdbcDataReader myreader;
myconn= new OdbcConnection( I removed this part );
mycmd = new OdbcCommand("insert into inventory
(Itemnum,Itemname,Itemdescription,Itemprice,Itemqoh,Itempicture) values
('"+ txtnum.Text +"','"+ txtname.Text +"','"+ txtdescription.Text
+"','"+ txtprice.Text +"','"+ txtqoh.Text +"','"+ txtpicture.Text
+"')",myconn);
myreader.Close();
myconn.Close();
%>
<br>
<center> <a href ="Company.html" > Back to our Homepage </a> </center>
be sure to use parameters! a question mark is used for each value you get from the user.
example below taken from https://www.mikesdotnetting.com/article/26/parameter-queries-in-asp-net-with-ms-access. (a great resource.)
string ConnString = Utils.GetConnString();
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
You need to bind the connection to command, and call command execution statement, e.g.:
...
mycmd.Connection = myconn;
mycmd.ExecuteNonQuery();
myconn.Close();
No reader needed.
The better way to operate the DB is:
using(OdbcConnection myconn = new OdbcConnection(connectionString))
{
using(OdbcCommand mycmd = OdbcCommand(your code here))
{
mycmd.Connection = myconn;
mycmd.ExecuteNonQuery();
}
}
For using keyword, it will be disposing the connection and command instance automatically.
Here I am trying to save the data in data base. Whatever data user enters it has to save in database and it has to save in page it self also. when user opens page that data has to display.
Code for aspx page
<asp:Label runat="server" ID="lblCnct" Text="Contact Number" AssociatedControlID="txtCnct" CssClass="control-label" />
<asp:TextBox runat="server" ID="txtCnct" CssClass="form-control" />
<asp:Label runat="server" ID="lblAltCnct" Text="Alternative Contact Number" AssociatedControlID="txtAltCnct" CssClass="control-label" />
<asp:TextBox runat="server" ID="txtAltCnct" CssClass="form-control" />
<asp:Label runat="server" ID="lblEmcnct" Text="Emergency Contact Number" AssociatedControlID="txtEmrCnct" CssClass="control-label" />
<asp:TextBox runat="server" ID="txtEmrCnct" CssClass="form-control" />
Button code saving the data in database
<button type="button" class="btn btn-primary" aria-label="Left Align" runat="server" onserverclick="btnContactInfoSave_click">
code for aspx.cs page
btnContactInfoSave_click code for saving the data in database.
protected void btnContactInfoSave_click(object sender, EventArgs e)
{
string[] ContactInfoData = new string[4];
ContactInfoData[0] = GlobalVars.UserEmail;
ContactInfoData[1] = txtCnct.Text;
ContactInfoData[2] = txtAltCnct.Text;
ContactInfoData[3] = txtEmrCnct.Text;
Utilities.sqlUploadContactInfoData(ContactInfoData);
}
}
public static void sqlUploadContactInfoData(string[] Userdata)
{
using (SqlConnection sqlConn = jPortalDBConnection())
{
try
{
sqlConn.Open();
string spName = "spUploadContactInfoData";
SqlCommand cmd = new SqlCommand(spName, sqlConn);
cmd.Parameters.AddWithValue("#txtCnct", Userdata[0].ToString());
cmd.Parameters.AddWithValue("#txtAltCnct", Userdata[1].ToString());
cmd.Parameters.AddWithValue("#txtEmrCnct", Userdata[2].ToString());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
cmd.ExecuteNonQuery();
}
catch (SqlException)
{
ErrorMsg("Server Error", "Server Error ! Please try again Later.");
}
}
}
After entering the data when I am trying to save the data it is not saving the data. button is not triggering. Any wrong in this code..???
Try with This. This is the way to Insert data into DB
SQL connection code for connecting database...
public static void sqlUploadContactInfoData(string[] Userdata)
{
using (SqlConnection sqlConn = jPortalDBConnection())
{
try
{
sqlConn.Open();
string spName = "spUploadContactInfoData";
SqlCommand cmd = new SqlCommand(spName, sqlConn);
cmd.Parameters.AddWithValue("#txtCnct", txtCnct.Text);
cmd.Parameters.AddWithValue("#txtAltCnct", txtAltCnct.Text);
cmd.Parameters.AddWithValue("#txtEmrCnct", txtEmrCnct.Text);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
cmd.ExecuteNonQuery();
}
catch (SqlException)
{
ErrorMsg("Server Error", "Server Error ! Please try again Later.");
}
}
}
From your web from designer double click on the button check weather it pointing to the Button event you expected to be invoked.else this will create a event handler for you.
If you are assigning the click handler in code behind, make sure that it is not inside an IsPostBack == false check :
make sure CausesValidation = "false" attribute of button like:
runat="server" and OnClick="btnContactInfoSave_click" check these attribute exist in your asp button
Try button in this way:
<asp:Button ID="AddMore_Button" class="btn btn-primary" runat="server" Text="" OnClick="btnContactInfoSave_click" />
here is some with my project. i want to add review form but in html form cause i already used server side for another reason.
here is html code:
<form id="modal_feedback" method="POST" action="#" accept-charset="UTF-8">
<p><label>Your Name<strong>*</strong><br>
<input runat="server" id="rvwname" type="text" autofocus required size="48" name="name" value=""></label></p>
<p><label>Email Address<strong></strong><br>
<input runat="server" id="rvwemail" type="email" title="Please enter a valid email address" size="48" name="email" value=""></label></p>
<p><label>Contact Number:*<br>
<input runat="server" id="rvwno" type="text" required size="48" name="contact" value=""></label></p>
<p><label>Message:<strong>*</strong><br>
<textarea runat="server" id="rvwmsg" required name="message" cols="48" rows="8"></textarea></label></p>
<p> <input runat="server" type="button" id="rvwsubmit" name="feedbackForm" value="Send" onserverclick="rvwsubmits" /> </p>
</form>
</div> <!-- #modal_window -->
</div> <!-- #modal_wrapper -->
and back end code of c# is:
protected void rvwsubmits(object sender, EventArgs e)
{
string a = rvwname.Value;
string b = rvwno.Value;
string c = rvwemail.Value;
string d = rvwmsg.Value;
string cnn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
MySqlConnection con = new MySqlConnection(cnn);
MySqlCommand cmd = new MySqlCommand("insert into ab_db.rvw(rvw_name,rvw_no,rvw_email,rvw_msg) values('" + a + "','" + b + "','" + c + "','" + d + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
You are having
value=""
for all the fields
Try this
value="#Request.Form["name"]"
value="#Request.Form["email"]"
My Experience & What I'm Using
So I'm just starting off with a very basic web application in ASP.NET to gain a little more familiarity with SQL Server Management Studios and Visual Studios 2010. Normally, I use MySQL, PHP, and Sublime Text Editor 2. I'm not very experienced with C# and implementing a database in Visual Studios. So I'm trying to use a stored procedure from SQL Server Management Studios and implement it in Visual Studios 2010.
The Issue
So here's my problem: I'm trying to create a basic webpage that links to a SQL Server and be able to add, delete, search and display all records from the database. Now I've written my own code based on what I thought was correct for add/delete and nothing happens when I click the buttons. So I'm sure you can see where my frustration derives from. I'm not sure if the issue is in my C# coding or in my SQL coding.
I'd like to focus on just getting my add/delete buttons to work and then to figure out the logic to display all files. I'd like to be able to click a button and then have it show all files instead of just displaying a grid. My database is called FirstApp.
Here's what's in my web.config file:
<add name="FirstApp" connectionString="Data Source=PCNAME\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True"
providerName="System.Data.SqlClient" />
Now this is what's in my Default.aspx.cs file:
*CORRECT CODE NOW!*
namespace FirstApp
{
public partial class _Default : System.Web.UI.Page
{
public string CommandArgument { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
private void MessageBox(string msg)
{
Label lbl = new Label();
lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
Page.Controls.Add(lbl);
}
//Add a new company to the database
protected void add_Click(object sender, EventArgs e)
{
SqlDataReader rdr = null;
string connectionString = null;
SqlConnection cnn;
connectionString = "Data Source=ITXDK29M91\\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True";
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand("dbo.Add_Company", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#companyname", companyname.Text);
cmd.Parameters.AddWithValue("#companyphone", companyphone.Text);
cmd.Parameters.AddWithValue("#companyid", companyid.Text);
cmd.Parameters.AddWithValue("#companytype", companytype.Text);
rdr = cmd.ExecuteReader();
}
finally
{
//Close the connections
if (cnn != null)
{
cnn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
//Delete a company from the database
protected void delete_Click(object sender, EventArgs e)
{
SqlDataReader rdr = null;
SqlConnection cnn;
string connectionString = null;
connectionString = "Data Source=ITXDK29M91\\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True";
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand("dbo.deleteCo", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID", SqlDbType.Int);
rdr = cmd.ExecuteReader();
}
finally
{
//Close the connections
if (cnn != null)
{
cnn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
protected void Search_Click(object sender, EventArgs e)
{
}
protected void Getall_Click(object sender, EventArgs e)
{
}
}
}
This is what's in my Source Code in Default.aspx
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2>Ready for an Adventure? Let's get started!
</h2> <hr />This is where you can enter information about your company.
<br />
<form method="post" action="">
Company Name:<br />
<asp:TextBox ID="companyname" runat="server"></asp:TextBox>
<br />
Company Phone Number:<br />
<asp:TextBox ID="companyphone" runat="server"></asp:TextBox>
<br />
Company Tax ID Number:
<br />
<asp:TextBox ID="companyid" runat="server"></asp:TextBox>
<br />
Type of business: <br />
<asp:TextBox ID="companytype" runat="server"></asp:TextBox>
<br />
<asp:Button ID="add" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="add_Click" Text="Submit" Width="128px" />
</form> <hr />
Want to delete your company information?<br />
Enter in the Company ID Number:
<br />
<asp:TextBox ID="PrimaryKey" runat="server" Width="120px"></asp:TextBox>
<br />
<asp:Button ID="delete" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="delete_Click" Text="Delete Info" Width="119px" />
<br />
<hr />
Looking for similar companies?
<br />
(Ex: Retail, Designer, Restaurant, etc.)
<br />
Enter the type of company:
<br />
<asp:TextBox ID="scompanyid" runat="server" Width="120px"></asp:TextBox>
<br />
<asp:Button ID="Search" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="Search_Click" Text="Start Searching!" Width="119px" />
<br />
<hr />
Want to see all the companies that we work with? <br />
Click the button below!
<br />
<asp:Button ID="Getall" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="Getall_Click" Text="Get all records!" Width="119px" />
<br />
<br />
</asp:Content>
UPDATE: I've updated the code to display the correct code. The add button works but my delete button is not. I'm still trying to figure that one out.
You're not actually opening a connection or executing your SQL commands. Generally, the way you execute a simple command is:
using (var conn = new SqlConnection(connectionString))
{
using (var comm = conn.CreateCommand())
{
conn.Open();
comm.CommandText = "SOME SQL HERE";
// command type, parameters, etc.
//pick one of the following
comm.ExecuteNonQuery();
int value = (int)comm.ExecuteScalar();
SqlDataReader reader = comm.ExecuteReader();
}
}
You need to actually execute the command. There are four types of execution (depending on the type of results you'll be expecting from your query statement)
ExecuteReader - Rows and columns returned (e.g. Normal select queries)
ExecuteNonquery - No results expected. (e.g. Deleting a record)
ExecuteScalar - Single value (e.g. Count, Max, etc..)
ExecuteXMLReader - For XML stuff
Something like this for the add
cmd.ExecuteNonquery();
Even before worrying about executing the command though, you always need an open connection through which you execute commands and you need to link your command to it:
SqlConnection cn = new SqlConnection(connStr);
cn.Command = cmd;
cn.Open();
<your command/parameter code here>
cmd.ExecuteNonquery();
And don't forget to put stuff back the way you found it:
cmd.Close();
cn.Close();
There are other suggestions I'd make--like making the phone number varchar since you're not going to do arithmetic on it as a number--but this is not your real question here and now.
Best wishes!
FYI: Side topic: Whenever you begin to use commands to return results, you will not need a "new" for your SqlDataReaders because commands executed with ExecuteReader create and return an SqlDataReader object. This means you can just do this
//This next line not needed
//dr = new SqlDataReader()
SqlDataReader dr = cmd.ExecuteReader();
It looks like you aren't executing your SQL statements. Try creating a method that does the below then call that method from your delete button click event.
public static void DeleteSomething()
{
using (var conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("usp_proc_delete", conn.CreateCommand()))
{
conn.Open()
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PrimaryKey", SqlDbType.Int);
cmd.ExecuteNonQuery();
}
}
}