Executing an INSERT command using ASP.net - c#

I am using Visual Studio 2010 to create a simple Website for a college assignment. I am trying to create a contact form that submits the users name, email and message to my database table Messages.
I have created the relevant web service and I know that it is working when I try to GET data from the Table. I am just a little confused as to how I can INSERT data into the table.
Below is the code to my web service. The method I am concerned with is addMessage() I call the method when a button is clicked that is located on the contact.aspx page.
public class Customers : System.Web.Services.WebService {
[WebMethod]
public DataSet getCustomers() {
SqlConnection conn;
SqlDataAdapter myDataAdapter;
DataSet myDataSet;
string cmdString = "Select * From Customers";
conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
myDataAdapter = new SqlDataAdapter(cmdString, conn);
myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "Customers");
return myDataSet;
}
[WebMethod]
public void addMessage(String n, String e, String m)
{
SqlConnection conn;
SqlDataAdapter myDataAdapter;
SqlCommand myCommand = new SqlCommand("INSERT INTO Messages VALUES("+n+","+e+","+m+")");
conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
//UNSURE WHAT TO DO FROM THIS POINT... CAN I USE myDataAdapter to execute a query?
}
}
Appreciate any help you guys might have! Thanks

[WebMethod]
public void addMessage(String n, String e, String m)
{
string sql = "INSERT INTO Messages VALUES(#n, #e, #m)";
using (var conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"))
using (var cmd = new SqlCommand(sql, conn))
{
//change these three lines to use actual database column types, lengths
//I'll pretend "e" is a date column just to show an example of how that might look
cmd.Parameters.Add("#n", SqlDbType.NVarChar, 50).Value = n;
cmd.Parameters.Add("#e", SqlDbType.DateTime).Value = DateTime.Parse(e);
cmd.Parameters.Add("#m", SqlDbType.NVarChar, 50).Value = m;
conn.Open();
cmd.ExecuteNonQuery();
}
}

Related

DataGridView does not show SOME data

I created an app for inserting specific data into database and it works fine.
However, when i try to view that data, DataGridView shows just some of those fields.
I stucked here. I tried to delete DataGridView and write code again, but it didn't helped.
private void displayData()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\me\Documents\DataB.mdf;Integrated Security=True;Connect Timeout=30";
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM dbo.Users ";
cmd.ExecuteNonQuery();
DataGrid.Update();
DataSet dt = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
DataGrid.DataSource = dt;
conn.Close();
}
I expected completely filled DataGridView, but some fields are empty.
I can see name, username, date of birth, than 5 empty cells, then again i can see salary, education and so on..

c# local Cannot open database requested by the login. The login failed. Login failed for user MicrosoftAccount\(email)

Doesnt connect to database, its throw exception.
SqlConnection con = new SqlConnection("Data Source=.;InitialCatalog=CAFETERIADB; Integrated Security=True;");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
DataSet ds = new DataSet();
private void CashForm_Load(object sender, EventArgs e)
{
con.Open();
da = new SqlDataAdapter("Select * FROM PhoneBook ORDER BY SLNo desc", con);
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Columns[0].Width = 10;
con.Close();
comboBox1.Items.Clear();
con.Open();
cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Name FROM PhoneBook order by SLNo asc";
cmd.ExecuteNonQuery();
dt = new DataTable();
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
da1.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["Name"].ToString());
}
con.Close();
here is my connection string:
<add name="CafeteriaDBConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CafeteriaDB.mdf;Integrated Security=True"
First of all, place your connection string in single location. As on connection string inside code and second in configuration file.
SqlConnection con = new SqlConnection("Data Source=.;InitialCatalog=CAFETERIADB; Integrated Security=True;");
To make it working first test your connection string.
Save notepad file as name.udl
double click and provide appropriate values if local server (pc name \SQLEXPRESS) or (.\SQLEXPRESS)
Click test and again open same udl file in notepad
copy the connection string it will be some thing like below but exclude provider part
Password=;Persist Security Info=True;User ID=;Initial Catalog=CafeteriaDB;Data Source=.\SQLEXPRESS
SqlConnection con = new SqlConnection("Password=***;Persist Security Info=True;User ID=***;Initial Catalog=CafeteriaDB;Data Source=.\SQLEXPRESS;")
I hope this will helps you.
I don't think in your code you are referring to the connection string you set up in config file. Instead, you hard-coded a new connection in the first line of your code.
If you are sure the connection string in config file works fine, you can put it into your code directly.
Change your first line code as:
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CafeteriaDB.mdf;Integrated Security=True");
Or you can refer to connection string in config file.
string connectionString = DatabaseHelper.CafeteriaDBConnectionString;
SqlConnection con = new SqlConnection(connectionString);

How to convert selected date to string and view on DataGrid

I'm trying to search for data between two dates and show on the datagrid. However I'm getting an error says that toString is unable to convert the selected date to string.
private void searchButton_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=xxxxxx;Password=xxxxxx");
SqlDataAdapter sda = new SqlDataAdapter("SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where JoiningDate between'"+fromText.SelectedDate.Value.ToString("MM/DD/YYYY")+"'AND'"+toText1.SelectedDate.Value.ToString("MM/DD/YYYY")+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
UPDATE:
I have changed my code and have gotten rid of the error. However, no data is showing on in the grid, only an empty row. Would anyone know why that is?
string sqlStr = "SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where RentDate between #fromDT AND #toDT";
string connStr = #"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=xxxxxx;Password=xxxxxx";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlDataAdapter sda = new SqlDataAdapter(sqlStr, con))
{
sda.SelectCommand.Parameters.Add(new SqlParameter("#toDT", SqlDbType.DateTime)).Value = toText1.SelectedDate.Value;
sda.SelectCommand.Parameters.Add(new SqlParameter("#fromDT", SqlDbType.DateTime)).Value = fromText.SelectedDate.Value;
DataSet ds = new DataSet();
con.Open();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
There are some issues in your code.
Your con connection string didn't' open when you use Fill method, so you can't execute the SQL statement.
Your code has a SQL-Injection problem, I would suggest you use parameters instead of connected SQL statement string, make sure your parameter data type size as same as your table schema.
You didn't return the resource when you finish you have executed your SQL statement, I would use using statement because the purpose of Using statement is that when control will reach the end of using it will dispose that object of using block and free up memory. its purpose is not only for auto connection close, basically it will dispose of the connection object and obviously, the connection also closed due to it.
using SqlParameter class to make it.
private void searchButton_Click(object sender, RoutedEventArgs e)
{
string sqlStr = "SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where JoiningDate between #fromDt AND #toDt";
string connStr = #"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=DDQ4_Melveena;Password=xxxxx";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlDataAdapter sda = new SqlDataAdapter(sqlStr, con))
{
sda.SelectCommand.Parameters.Add(new SqlParameter("#toDt", SqlDbType.DateTime)).Value = toText1.SelectedDate.Value;
sda.SelectCommand.Parameters.Add(new SqlParameter("#fromDt", SqlDbType.DateTime)).Value = fromText.SelectedDate.Value;
DataSet ds = new DataSet();
con.Open();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
}

can't read int value from sql database

I have tried this code in C#, and it's not working - I can't get an input id, every time I run it, the value of id is 0.
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco");
int id;
con.Open();
string sql = "select * from Staff_Management where Emp_Name = '"+sName+"'; ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader read = cmd.ExecuteReader();
if (read.Read())
{
id = read.GetInt32(0);
TM_AC_SelectId.Text = id.ToString();
}
else
{
MessageBox.Show("Error 009 ");
}
con.Close();
You should try to follow the accepted best practices for ADO.NET programming:
use parameters for your query - always - no exceptions
use the using(...) { .... } construct to ensure proper and quick disposal of your resources
select really only those columns that you need - don't just use SELECT * out of lazyness - specify your columns that you really need!
Change your code to this:
// define connection string (typically loaded from config) and query as strings
string connString = "Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco";
string query = "SELECT id FROM dbo.Staff_Management WHERE Emp_Name = #EmpName;";
// define SQL connection and command in "using" blocks
using (SqlConnection con = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// set the parameter value
cmd.Parameter.Add("#EmpName", SqlDbType.VarChar, 100).Value = sName;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
con.Close();
int id;
if(result != null)
{
if (int.TryParse(result.ToString(), out id)
{
// do whatever when the "id" is properly found
}
}
}

Working on SQL Queries in C#

Is there a better way of implementing multiple SQL queries? I had tried this; it works fine, but I think it's not efficient.
static void Main(string[] args)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\MUHAMMAD\Documents\samEE.mdf;Integrated Security=True;Connect Timeout=30";
SqlCommand cmd = new SqlCommand("Select * from Student", con);
con.Open();
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine("Id is:"+dr[0]+" Name is:"+ dr[1]);
}
con.Close();
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\MUHAMMAD\Documents\samEE.mdf;Integrated Security=True;Connect Timeout=30";
SqlCommand cmd2 = new SqlCommand("Select Name from Student", con2);
con2.Open();
SqlDataReader dr2;
dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
Console.WriteLine("Name is :"+ dr2[0]);
}
con2.Close();
Console.ReadKey();
}
Your sample makes no sense. You query two times for the same table. In the first query you get back all the column from the Student table and then you use only the ID and Name fields, in the second one you get back just the student name, but this was already available in the first query
Just one query could be enough (and apply the using statement to properly close and dispose the objects involved)
string conString = ".....";
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd = new SqlCommand("Select ID, Name from Student", con))
{
con.Open();
using( SqlDataReader dr = cmd.ExecuteReader())
while (dr.Read())
{
Console.WriteLine("Id is:"+dr[0]+" Name is:"+ dr[1]);
}
}
If you want to execute two queries in the same time, you could append the two queries to the same command separating them with a semicolon
using(SqlCommand cmd = new SqlCommand("Select ID, Name from Student;" +
"Select CourseID, CourseName from Course", con))
In this example you get back two set of records, one for the Student table and one for Course table. When you call the ExecuteReader, the readear is positioned on the first result set (the Student list), but you enclose this loop in a do/while block that will control the switch to the second result set (the Course) when the first has been totally read
using(SqlDataReader reader = cmd.ExecuteReader())
{
do
{
// First time reads the student, when finished, the NextResult call switch the reader
// on the second set and then exits (because there are no more result sets)
while(reader.Read())
{
}
}while(reader.NextResult());
Is there a Better way of implementing multiple Queries.
Re-use the connection string
string connString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\MUHAMMAD\Documents\samEE.mdf;Integrated Security=True;Connect Timeout=30";
use using on connections, commands, and readers:
using SqlConnection con = new SqlConnection(connString))
{
using(SqlCommand cmd = new SqlCommand("Select * from Student", con))
{
....
}
}
Your contrived example pulls the same values from the same table in two separate queries, so I don't know what your real-world example would be to make it better. Why can;t you just re-use the values pulled from the first query?
You already have name in your first query, so why use second query to fetch name.
Few general points :
Acquire connection as late as possible, and, close them early.
Re-usable connection instead of opening a new connection every time a connection request to the database is made by the application.
When you are specifying the connection string, ensure that you specify the IP address of the database server to connect to,
rather than the Database Server’s DNS name.
Credit goes to
static void Main(string[] args)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\MUHAMMAD\Documents\samEE.mdf;Integrated Security=True;Connect Timeout=30";
SqlCommand cmd = new SqlCommand("Select Id,Name from Student", con);
con.Open();
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine("Id is:"+dr[0]+" Name is:"+ dr[1]);
}
con.Close();
con.Dispose();
Console.ReadKey();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
finally
{
if(con.State == ConnectionState.Open)
con.Close();
}
}
Also check this whether the ADO.NET DataReader or the DataSet is the better tool.
Try this..
static void Main(string[] args)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\MUHAMMAD\Documents\samEE.mdf;Integrated Security=True;Connect Timeout=30";
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Student", con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine("Id is:"+dr[0]+" Name is:"+ dr[1]);
}
dr.Close();
//con.Close();
//SqlConnection con2 = new SqlConnection();
//con2.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\MUHAMMAD\Documents\samEE.mdf;Integrated Security=True;Connect Timeout=30";
cmd = new SqlCommand("Select Name from Student", con);
//con2.Open();
SqlDataReader dr2;
dr2 = cmd.ExecuteReader();
while (dr2.Read())
{
Console.WriteLine("Name is :"+ dr2[0]);
}
dr2.Close();
con.Close();
Console.ReadKey();
}
You can pass multiple queries to a single SqlCommand separated by semicolon. Then you can iterate through the data reader like you currently do and at the end request the next query result via dr.NextResult method.
Here's a basic code sample
SqlCommand cmd = new SqlCommand("SELECT Something1 FROM Table1;SELECT Something2 FROM Table2" , con)
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
do {
while (dr.Read())
{
// do stuff with results
}
} while (dr.NextResult())
Outer loop iterates thru query results while inner loop goes thru individual rows of current result.

Categories