How to connect to SQL Server with asp.net - asp.net

I want to connect to SQL Server with ASP.NET. Can any one give me some sample program to do so?

Here's an example
http://www.beansoftware.com/ASP.NET-Tutorials/ASP.NET-SQL-Server.aspx
Good Luck!

June R's example is inserting data.
using System.Data;
using System.Data.SqlClient;
string Connection = "server=ALDAN; uid=sa; pwd=sa; database=GAZCAD; Connect Timeout=10000";
SqlConnection DataConnection = new SqlConnection(Connection);
// the string with T-SQL statement, pay attention: no semicolon at the end of //the statement
string Command = "Select * from myTable";
// create the SQLCommand instance
SQLCommand DataCommand = new SqlCommand(Command, DataConnection);
// open the connection with our database
DataCommand.Connection.Open();
// Data adapter
SqlDataAdapter da = new SqlDataAdapter(DataCommand);
// To fill data, i need a datatable.
DataTable dt = new DataTable();
// Filling my table
da.Fill(dt);

Related

Post Error when submitting Angular form data to Azure SQL Database

I have a fully working ASP.NET Angular website that saves a form data to a database. I have managed to deploy it to Azure App Service and also connected to Azure SQL Database using visual studio. However when I save the form I have a post error. This is my first time, is there anything else that I need to do in order for the form to work because initially it was working with my local database?.
This is a screenshot of the error
I am creating an Azure SQL database and inserting data from asp.net. Connection_time_out error comes when the application is not connected to the server.
Create Azure SQL Database and create the table.
C# code for insert data into Azure Sql Database.
static void Main(string[] args)
{
//Connection String
string cs = "Server=tcp:xxx.database.windows.net,1433;Initial Catalog=punitdb;Persist Security Info=False;User ID=xxx;Password=xxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
SqlConnection con;
SqlDataAdapter adapt;
DataTable dt;
con = new SqlConnection(cs);
con.Open();
SqlCommand cmd;
string s = "insert into Persons values(#PersonID,#LastName,#FirstName,#email,#message)";
cmd = new SqlCommand(s, con);
cmd.Parameters.AddWithValue("#PersonID", 1);
cmd.Parameters.AddWithValue("#LastName", "Kumar");
cmd.Parameters.AddWithValue("#FirstName", "Roshan");
cmd.Parameters.AddWithValue("#email", "Roshan#gmail.com");
cmd.Parameters.AddWithValue("#message", "Hello Roshan");
cmd.CommandType = CommandType.Text;
int i = cmd.ExecuteNonQuery();
con.Close();
Console.WriteLine("Press Any key for Show data ");
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select top 1 * from Persons order by PersonID desc", con);
dt = new DataTable();
adapt.Fill(dt);
Console.WriteLine("First Name :-" + dt.Rows[0][2] + ", Last Name :-" + dt.Rows[0][1] + ", Emamil :-" + dt.Rows[0][3] + ", Message :- " + dt.Rows[0][4]);
Console.ReadKey();
}
code output
After running code
Microsoft document on Connection timeout expired errors
Read this Microsoft document for Common connection issue steps to fix common connection issues

Asp.net "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."

I am facing one problem in asp.net Application with sql server database.
I am getting Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
In my code stored procedure is taking around 43 seconds and after 30 seconds
I am getting this error. For Solving this I have analyzed many sites and found these solutions:
I need to set Connection Timeout=300 in connectionString in web.config file.
This point I have done, but still I get the same error.
I also need to set commandTimeout through code.
My problem : I am not able to modify the default commandTimeout
Because I am using DataTier_Using_SQLClient to connect to database.
This does not contain the commandTimeout property .
Actually default command timeout is 30 seconds only.
Assuming you are using an Adapter
DataSet dsData = new DataSet();
SqlConnection conn = new SqlConnection(GetConnection());
SqlDataAdapter adapter = new SqlDataAdapter(strQuery, conn);
adapter.SelectCommand.CommandTimeout = 120;
Thank you very much Tim B James and January Mmako
Actually I was solving one issue related to one application.
DataTier_Using_SQLClient is one class in my application to connect with Database.
Then forget this class.
I have solved this issue by creating connection using SqlConnection.
See the code below. Using this code you can solved the Time Expired Error
and can call retrieve stored procedure having one parameter that need to pass:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
use the below code where you want
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter ;
SqlCommand command = new SqlCommand();
SqlParameter param ;
DataSet ds = new DataSet();
//You can specify this connectionString in web.config or here
connetionString = "Data Source=servername;
Initial Catalog=PUBS;User ID=sa;
Password=yourpassword;
Connection Timeout=300";
connection = new SqlConnection(connetionString);
connection.Open();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_Retrieve_ProcedureName";
param = new SqlParameter("#paramName", ParamValue);
param.Direction = ParameterDirection.Input;
param.DbType = DbType.Int32;
command.Parameters.Add(param);
adapter = new SqlDataAdapter(command);
adapter.SelectCommand.CommandTimeout = 120;
adapter.Fill(ds);
you can use this ds (DataSet) object where ever you want.

Sql helper class in asp.net

Why should we use sql helper class in our application.What difference between sql helper class and simple class.In which situation sql Helper should used.Please define structure of class.
SqlHelper is intended to consolidate mundane, repetitive code that is written time and time again in data access layer components of ADO.NET applications, like this:
using Microsoft.ApplicationBlocks.Data;
SqlHelper.ExecuteNonQuery(connection,"INSERT_PERSON",
new SqlParameter("#Name",txtName.Text),
new SqlParameter("#Age",txtAge.Text));
Instead of this:
string connectionString = (string)
ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand("INSERT_PERSON",connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Name",SqlDbType.NVarChar,50));
command.Parameters["#Name"].Value = txtName.Text;
command.Parameters.Add(new SqlParameter("#Age",SqlDbType.NVarChar,10));
command.Parameters["#Age"].Value = txtAge.Text;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
It is part of the Microsoft Application Blocks framework.

how to connect MYSQL server using ASP.NET?

I want to use MYSQL server with my asp.net application. But i am not able to connect to it. I am getting error that is "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified " .
My code is:-
System.Data.Odbc.OdbcConnection cn = new System.Data.Odbc.OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=new_testdb; User=root;Password=abc123#;");
cn.Open();
System.Data.Odbc.OdbcCommand cmd = new System.Data.Odbc.OdbcCommand();
System.Data.Odbc.OdbcDataAdapter adp = null;
DataSet ds = new DataSet();
cmd.Connection = cn;
cmd.CommandText = "Select * from new_table";
adp = new System.Data.Odbc.OdbcDataAdapter(cmd);
adp.Fill(ds, "new_table");
this.GridView1.DataSource = ds;
this.GridView1.DataMember = "new_table";
cn.Close();
Try to download ADO.NET MySql Connector API (managed MySql Data provider) instead of ODBC Driver.
EDIT: Connector/NET Examples
You also may connect to MySQL with dotConnect for MySQL components.
Try to build the connection string with MySqlConnectionStringBuilder class.
This is what you need: http://dev.mysql.com/downloads/connector/net
Enjoy!
Could you please see here My SQL ConnectionString or ConnectionString
Click Left btn on database in server explorer, select properties copy connection string;
2.string c= persistsecurityinfo=True;server=localhost;user id=root;password=admin;database=sam;
MySqlConnection cn = new MySqlConnection(c);
cn.Open();
Response.Write("Connection successful !!");
MySqlDataAdapter Mda = new MySqlDataAdapter("select * from tblName", cn);
DataSet ds = new DataSet();
Mda.Fill(ds, "tblName");
GridView1.DataSource = ds.Tables["tblName"];
GridView1.DataBind();
Make sure that :-
using System.Data;
using MySql.Data.MySqlClient;
imported... :)

Execute SQL stored using ado.net

I am using ado.net to access sql server I have costum Stored Procedure I am executing it using ado.net :
SqlCommand command = new SqlCommand("Custom",con);
and i am sending the parameters like this :
command.Parameters.Add(new SqlParameter("#Parm1",SqlDbType.Int,0,"Parm1"));
command.Parameters.Add(new SqlParameter("#Parm2",SqlDbType.Int,0,"Parm2"))
it dose not work and it did not give me an error as well it is the first time to work without DAL generator
Please, use this pattern:
SqlCommand command = new SqlCommand("nameOfMyStoredProcedure", mySqlConnectionObject);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#ID", SqlDbType.Int);
command.Parameters["#ID"].Value = customerID;
to make it work add this line before set the params :
command.CommandType = CommandType.StoredProcedure;
and set the params using :
command.Parameters[0].Value=4;
command.Parameters[1].Value=2;
:)

Resources