how to do a insert statement in web service asp.net - asp.net

i am suppose to receive the data from android to my web service and my web service is going to insert the data into my data base. how am i going to do about it to insert the data from my web service to database.
this is my start of code :
[WebMethod]
public StudentTransactions GetStudentTransactions(string Name, string CLass, string NRIC, int StallNo, float AmountSpent)
{
SqlCommand sql1 = new SqlCommand("INSERT Into StudentTransactions (Name, CLass,NRIC,StallNo,AmountSpent) VALUES (Name,CLass,NRIC,StallNo,AmountSpent)");
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ncpsdbbConnectionString2"].ConnectionString))
{
conn.Open();
{
}
}

using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ncpsdbbConnectionString2"].ConnectionString))
{
SqlCommand command = new SqlCommand("INSERT Into StudentTransactions (Name, CLass,NRIC,StallNo,AmountSpent) VALUES (#Name,#CLass,#NRIC,#StallNo,#AmountSpent)");
command.Connection.Open();
command.ExecuteNonQuery();
}
Add the values and params like so:
command.Parameters.AddWithValue("#ParamName", [Some Value]);
Try the above.
Read more here:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx

Related

Need help reading multiple values back from sql server database in asp code

here is my codebehind for grabbing data from database:
public static string getTestimonial()
{
string username = "xxxxx";
SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["xxxxxxx"].ConnectionString);
Conn.Open();
string sql = "select testimonial,submitname from (SELECT TOP 1 * FROM dbo.testimonials where username='" + username + "' ORDER BY newid()) as answer;";
SqlCommand cmd = new SqlCommand(sql, Conn);
string test=cmd.ExecuteScalar().ToString();
Conn.Close();
return test;
}
yet when I try to display the data on my aspx page all I get is the first value:
<div class="span3">
<%= getTestimonial() %>
</div>
can you please help me with a method of getting both the testimonial and the submitname from the query into variables?
Thanks!
Thanks! Solved! using:
public static string getTestimonial()
{
string username = "xxxxxx";
SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["xxxxxxx"].ConnectionString);
Conn.Open();
string sql = "select testimonial,submitname from (SELECT TOP 1 * FROM dbo.testimonials where username='" + username + "' ORDER BY newid()) as answer;";
SqlCommand cmd = new SqlCommand(sql, Conn);
var test = new StringBuilder();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
test.Append(reader.GetString(0));
test.Append(" and ");
test.Append(reader.GetString(1));
}
}
Conn.Close();
return test.ToString();
}
ExecuteScalar() will always return first column of the first row - a single value. You may want to rethink your approach, meanwhile the simplest way is to make your query return combined value:
string sql = "select testimonial + ' and ' + submitname from ....
As an aside, you probably should rewrite that function to not use inline SQL, as you are making your site vulnerable to SQL injection attacks potentially in writing it this way. (presumably, userid is not set as a constant XXXXX in the actual function and is instead passed in somehow).

Execute select query from code behind

How can i execute a SELECT query from my Code Behind file and then iterate through it?
I want to do something like this (just a simple pseudo example):
// SQL Server
var results = executeQuery("SELECT title, name FROM table");
foreach (var row in results)
{
string title = row.title;
string name = row.name;
}
How can i do this within code?
Something like this:
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["OrderID"], reader["CustomerID"]));
}
}
}
Source: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx
The connectionString will vary depending on the Database product and the authentication mechanism used (Windows Auth, username/password, etc.). The example above assumes you are using SQL Server. For a complete list of different ConnectionStrings, go to http://www.connectionstrings.com/

how to use the passed parameters to the asp.net webservice in a sql statement?

hello i build a webservice to communicate with the iPhone.
i want to display the rooms from the selected street in a table, to do that i must to pass some id's from my iPhone with JSON to the sql database over a asp.net webservice.
my webmethod look like this:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public string Room(string street_id, string country_id, string city_id)
{
return RoomHelper.Room(street_id, country_id, city_id);
}
My sql statement should look like this:
SELECT Roomname FROM Room WHERE street_id = (passed street_id) AND country_id = (passed country_id) AND city_id = (passed city_id)
how can i use the passed parameters in my sql statement to filter the rooms ?
using (SqlConnection conn = new SqlConnection("<my connection string>"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Roomname FROM Room WHERE street_id = #streetId AND country_id = #countryId AND city_id = #cityId", conn))
{
cmd.Parameters.AddWithValue("#streetId", street_id);
cmd.Parameters.AddWithValue("#countryId", country_id);
cmd.Parameters.AddWithValue("#cityId", city_id);
using (var reader = cmd.ExecuteReader())
{
// retrieve your data per row or as you wish
while (reader.Read())
{
}
}
}
}

link data from Textbox to SQL Database in ASP.net (C#)

I am attempting to create a web form where data from several text box's will enter data into a n SQL database I have created. My code is listed below, and the problem is that when it compiles, it acts as if it hasn't. The messagedisplay.text does not change, and the SQL database does not update. Does anyone know a solution?
protected void createButton_Click(object sender, EventArgs e)
{
string state = stateTextBox.Text;
string country = countryTextBox.Text;
string lake = lakeTextBox.Text;
SqlConnection connection = new SqlConnection("Data Source=.MetricSample;Initial Catalog=ElementID;"+ "Integrated Security=true;");
connection.Open();
try
{
using (SqlCommand command = new SqlCommand(
"INSERT INTO ResearcherID VALUES(#ResearcherFname, #ResearcherLName)", connection))
{
command.Parameters.Add(new SqlParameter("ResearcherFName", country));
command.Parameters.Add(new SqlParameter("ResearcherLName", state));
command.ExecuteNonQuery();
}
messageDisplay.Text = "DB Connection Successfull";
}
catch
{
messageDisplay.Text = "DB Connection Failed";
}
}
try this
using (SqlCommand sqlCmd = new SqlCommand("INSERT INTO ResearcherID (FieldNameForFirstName, FieldNameForLastName) VALUES (#ResearcherFname, #ResearcherLName)", sqlConn)) {
sqlCmd.Parameters.AddWithValue("#ResearcherFname", country);
sqlCmd.Parameters.AddWithValue("#ResearcherLName", state);
}
Also use connection.Open(); inside try

Asp.Net select in Sql

This is going to be very simple I know. I have seen so many different ways of using sql in asp.net with no real standard. What I want to know is how to cleanly select from an sql database in asp.net and retrieve multiple records. For example: select all userids.
String sql =
"SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"]
.ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
/*
This is where I need to know how to retrieve the information from the
above command(comm). I am looking for something similiar to php's
mysql_result. I want to access the records kind of like an array or some
other form of retrieving all the data.
Also when the new SqlCommand is called...does that actual run the
SELECT STATEMENT or is there another step.
*/
conn.Close();
I think that this is what you are looking for.
String sql = "SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader nwReader = comm.ExecuteReader();
while (nwReader.Read())
{
int UserID = (int)nwReader["UserID"];
// Do something with UserID here...
}
nwReader.Close();
conn.Close();
I do have to say, though, that the overall approach can use a lot of tuning. First, you could at least start by simplifying access to your ConnectionString. For example, you could add the following to your Global.asax.cs file:
using System;
using System.Configuration;
public partial class Global : HttpApplication
{
public static string ConnectionString;
void Application_Start(object sender, EventArgs e)
{
ConnectionString = ConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
}
...
}
Now, throughout your code, just access it using:
SqlConnection conn = new SqlConnection(Global.ConnectionString);
Better yet, create a class in which the "plumbing" is hidden. To run the same query in my code, I'd just enter:
using (BSDIQuery qry = new BSDIQuery())
{
SqlDataReader nwReader = qry.Command("SELECT...").ReturnReader();
// If I needed to add a parameter I'd add it above as well: .ParamVal("CurrentUser")
while (nwReader.Read())
{
int UserID = (int)nwReader["UserID"];
// Do something with UserID here...
}
nwReader.Close();
}
This is just an example using my DAL. However, notice that there is no connection string, no command or connection objects being created or managed, just a "BSDIQuery" (which does lots of different things in addition to that shown). Your approach would differ depending on the tasks that you do most often.
Most of the time, I use this (note that I am also using a connection pooling approach):
public DataTable ExecuteQueryTable(string query)
{
return ExecuteQueryTable(query, null);
}
public DataTable ExecuteQueryTable(string query, Dictionary<string, object> parameters)
{
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
if (parameters != null)
{
foreach (string parameter in parameters.Keys)
{
cmd.Parameters.AddWithValue(parameter, parameters[parameter]);
}
}
DataTable tbl = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(tbl);
}
return tbl;
}
}
}
Here's an adaption of your existing code:
String sql = "SELECT [UserId] FROM [UserProfiles] WHERE [UserId] != #CurrentUserId";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
DataTable result = new DataTable();
using (var conn = new SqlConnection(strCon))
using (var cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#CurrentUserID", SqlDbType.Int).Value = CurrentUserID;
conn.Open();
result.Load(cmd.ExecuteReader());
}
Creating a SqlCommand doesn't execute it at all.
The command will be executed when you call ExecuteReader or something similar.
If you want something which will fetch all the results into memory, you should be looking at DataSet/DataTable. There's a tutorial for them here - or there are plenty of others on the net, and any decent ADO.NET book will cover them too.
If you don't want to fetch them all into memory at once, then ExecuteReader it the method for you. That will return a SqlDataReader which is like a database cursor - it reads a row at a time, and you ask for individual columns as you want them, calling Read to get to the next row each time.
Whereas in PHP you'd do something like,
while ($row = mysql_fetch_array ($result))
{
//this assumes you're doing something with foo in loop
$foo = $row["userid"];
//using $foo somehow
}
in .NET, you do something different. Believe me, originating from a PHP background, the transition from PHP to .NET is not easy. There's a lot of things that will seem bizarre. After a while though, it will make sense! Just stick it out. I personally like it better.
Ok.. assuming you have a DataSet like you say, you can do something like this,
//assuming you have a DataSet called myDataSet
for (int i = 0; i < myDataSet.Tables[0].Rows.Count; i++)
{
//likewise assuming here you're doing something with foo in loop
string foo = myDataSet.Tables[0].Rows[i]["userid"].ToString();
//similarly do something with foo in loop
}
That does the same thing as the PHP snippet.

Resources