I think what I need is simple but I can't achieve it through asp.net because I am a total beginner.
What I need is to display a field from sql db table to my webpage like this example:
Account Information
Your Name is: <Retrieve it from db>
Your Email is: <Retrieve it from db>
How should I do that ?
I already have table members.
I need to do this with c# , I am using Visual Studio Web Express 2010
First step is add the SQL Client namespace:
using System.Data.SqlClient;
DB Connection
Then we create a SqlConnection and specifying the connection string.
SqlConnection myConnection = new SqlConnection("user id=username;" +
"password=password;server=serverurl;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
This is the last part of getting connected and is simply executed by the following (remember to make sure your connection has a connection string first):
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
SqlCommand
An SqlCommand needs at least two things to operate. A command string, and a connection. There are two ways to specify the connection, both are illustrated below:
SqlCommand myCommand = new SqlCommand("Command String", myConnection);
// - or -
myCommand.Connection = myConnection;
The connection string can also be specified both ways using the SqlCommand.CommandText property. Now lets look at our first SqlCommand. To keep it simple it will be a simple INSERT command.
SqlCommand myCommand= new SqlCommand("INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)", myConnection);
// - or -
myCommand.CommandText = "INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)";
SqlDataReader
Not only do you need a data reader but you need a SqlCommand. The following code demonstrates how to set up and execute a simple reader:
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from table",
myConnection);
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
Console.WriteLine(myReader["Column1"].ToString());
Console.WriteLine(myReader["Column2"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Related
How to save a string in SQL Server as SqlDateType by using Visual Studio 2013? My string which I want to save is 1996-25-04. I am working with C#.
I have tried this as far
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=sa;Password=pass");
con.Open();
string sql = " insert into Staff_Management values( '" + TM_Add_BirthDate.Value.ToString() + "' ";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved successfully");
You should NEVER EVER concatenate together your SQL statements like this! This opens all doors to SQL injection attacks - and causes trouble with string and date values.
Try this code instead - using a parametrized query:
// define the query - and I'd recommend to always define the name of the columns you're inserting into
string query = "INSERT INTO dbo.Staff_Management(name-of-column-here) VALUES (#Birthdate);";
// define connection and command
// also: do **NOT** use the `sa` user for your production code!
using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=sa;Password=pass"))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// add the parameter - and use the proper datatype - don't convert all dates to strings all the time!
cmd.Parameters.Add("#Birthdate", SqlDbType.Date).Value = TM_Add_Birthdate.Value;
// open connection, execute INSERT query, close connection - done
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved successfully");
}
I have successfully created connection of database but now I'm having problem in insertion of data. Here is my code:
String Connection = null;
SqlConnection con;
SqlCommand cmd;
String sql = null;
Connection="Data Source=DELL\\SQLEXPRESS; initial Catalog= BSSE;Integrated Security=True";
con = new SqlConnection(Connection);
sql = "INSERT INTO Records (Roll_No,Name,Marks) VALUES (" + textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + ");";
try
{
con.Open();
cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
MessageBox.Show ("Success of data insertion ");
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
First, your SQL statement is incorrect. You are missing single quote between values field. Later, you build SQL statement by using string concatenation and this is dangerous because can be exposed to SQL Injection. Use Parameterized Query instead.
try
{
con.Open();
cmd = new SqlCommand("INSERT INTO Records (Roll_No,Name,Marks) VALUES (#rollNo, #Name, #Marks)", con);
cmd.Parameters.AddWithValue("#rollNo", textBox1.Text);
cmd.Parameters.AddWithValue("#Name", textBox2.Text);
cmd.Parameters.AddWithValue("#Marks", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show ("Success of data insertion ");
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Check your connection string. I usually write it as:
string Connection = #"Data Source=DELL\SQLEXPRESS;Initial Catalog = BSSE; Integrated Security = true";
If the roll number is supposed to be an integer, you need to parse
it.
int.Parse(textBox1.Text)
I suggest to use store procedures instead of sending blocks of SQL code from the c# Application, here is a reference to the SQL Store Procedures: https://msdn.microsoft.com/en-us/library/ms190782.aspx. You can reduce the possibility of SQL injection by adding parameters to your query instead of plain text, also you need to validate the input. You can create calls with parameters too. There are many ways to call a SQL database query from C#, Here is more information about Store Procedures that can give you a clue: http://csharp-station.com/Tutorial/AdoDotNet/Lesson07
As a group we are working on a project and need to save the data collected in the label in a field in an access database. However we have been having some troubles with this function.
Here is the code what i have tried so far:
We changed the values from lbl.View.text to "1" for testing purposes, but still no luck.
private void complete_btn_Click(object sender, EventArgs e)
{
string connStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\meSch\log.accdb;Persist Security Info=True";
OleDbConnection con = new OleDbConnection();
con.ConnectionString = connStr;
OleDbCommand cmd = con.CreateCommand();
// error is in insert statement somehwhere.
cmd.CommandText = "INSERT INTO Users (TimeStamp, Interest, TotalTime)" + "VALUES('" + "1" +"', '"+ "1" + "','" + "1" + "');";
// conn1 = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\meSch\log.accdb;Persist Security Info=True");
// cmd = new OleDbCommand("", con);
// cmd.Parameters.AddWithValue("#TimeStamp", lblView.Text);
// cmd.Parameters.AddWithValue("#Interest", lblView.Text);
// cmd.Parameters.AddWithValue("#TotalTime", lblView.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Based on your exception message, TimeStamp is a reserved keyword in MS Access. You need to use it with square brackets like [TimeStamp]. As a better way, change it to non-reserved word which is meaningful for your column.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection con = new OleDbConnection(conString))
using(OleDbCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"INSERT INTO Users (TimeStamp, Interest, TotalTime)
VALUES(?, ?, ?)";
cmd.Parameter.AddwithValue("#p1", "1");
cmd.Parameter.AddwithValue("#p2", "1");
cmd.Parameter.AddwithValue("#p3", "1");
con.Open();
cmd.ExecuteNonQuery();
}
I am trying to insert data into a database that I have that has a table called EmployeeInfo
The user is prompted to enter a last name and select a department ID (displayed to the user as either marketing or development) The column ID automatically increments.
Here is my Code behind
protected void SubmitEmployee_Click(object sender, EventArgs e)
{
var submittedEmployeeName = TextBox1.Text;
var submittedDepartment = selectEmployeeDepartment.Text;
if (submittedEmployeeName == "")
{
nameError.Text = "*Last name cannot be blank";
}
else
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("ConnString");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO EmployeeInfo (LastName, DepartmentID ) VALUES ('" + submittedEmployeeName + "', " + submittedDepartment + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
The error I'm recieving is 'Arguement exception was unhandled by user code'
Here is a picture of it.
As requested. More details
If I had enough reputation, I would rather post this as a reply, but it might actually be the solution.
The reason why it stops there is because you are not providing a legit SqlConnection, since your input is: "ConnString", which is just that text.
The connection string should look something like:
const string MyConnectionString = "SERVER=localhost;DATABASE=DbName;UID=userID;PWD=userPW;"
Which in your case should end up like:
System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(MyConnectionString);
Besides that, you should build your connections like following:
using (SqlConnection con = new SqlConnection(MyConnectionString)) {
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = xxxxxx; // Your query to the database
cmd.Connection = con;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
This will do the closing for you and it also makes it easier for you to nestle connections. I did a project recently and did the connection your way, which ended up not working when I wanted to do more than one execute in one function. Just important to make a new command for each execute.
I am working on WPF application in C#. Database is SQL Server 2008. I have a table "Employee" in database, I need to insert a row in it. I have successfully connected with database, but when I tried to execute this line:
cmd = new SqlCommand(cmdText, conn);
This errors comes up: The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(String, System.Data.SqlClient.SqlConnection)' has some invalid arguments.
Here is my code:
private void addbtn_Click(object sender, RoutedEventArgs e)
{
//FUNCTION TO ADD NEW EMPLOYEE RECORD IN DATABASE
try
{
conn.ConnectionString = "Data Source=AZEEMPC;" + "Initial Catalog=IEPL_Attendance_DB;";
conn.Open();
cmdText = "INSERT INTO Employee VALUES ('" + strCurrentString + "','" + emp_name.Text + "')";
cmd = new SqlCommand(cmdText, conn);
data_ad = new SqlDataAdapter(cmd);
data = new DataSet();
data_ad.Fill(data);
MessageBox.Show("Record Inserted Successfully!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any suggestions?
conn needs to be of type SqlConnection - can you confirm that it is?
SqlConnection conn;
Because it's a native SQL Server connection, you don't need to pass the driver name in the connection string.
conn.ConnectionString = "Server=AZEEMPC;Database=IEPL_Attendance_DB;Trusted_Connection=true;";