I have developed a asp.net web application using visual studio 2010. I'm using SQL server 2008 as database. I need to fetch data from one of the remote server through LAN connection and have to store to my database through C# code. I am beginner to web development using asp.net and C#. please tell me a very simple way to solve this.
This is an example which I tried. Is this code OK or wrong please guide me with this?
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = #"Data Source=172.16.7.127\inhouse;User ID=****;Password= *****;";
con1.Open();
string str = "select * from t_his_events Where patientMRN="+hosp_no.Text;
SqlDataReader dr;
SqlCommand myCommand = new SqlCommand(str,con1);
dr = myCommand.ExecuteReader();
if (dr.HasRows)
{
Console.WriteLine("connection established");
}
}
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection(<connectionstring>);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM table";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
And now you have a DataSet containing the results of your query. As for determining your , I suggest Connection Strings as a great resource for picking the perfect format.
Where is your database name in connectionString you created on remote server
using System.Data.SqlClient;
using system.Data;
string cs = Data Source=172.16.7.127\inhouse;database=databasename;User ID=User id create on remote server;Password= Your password for the ;
SqlConnection conn = new SqlConnection(cs);
SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM tableName",conn);
DataSet ds = new DataSet();
adp.Fill(ds);
now you can use the dataset object that contain your table
Related
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
I was trying database connection. But I am getting this error. Please help me.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace OLSWebApp
{
public partial class ItemTypeWebForm : System.Web.UI.Page
{
static string constr = "server=DESKTOP-3N4UH9N; user=sa; pwd=ZEESHAN#123; Initial Catalog=Online Order System";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SaveButton_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(constr);
conn.Open();
string q = "Insert INTO ItemType values ('"+ TypeIdTextBox.Text +"'), ('"+ TypeTextBox.Text +"'),('"+ NameTextBox.Text +"')";
SqlCommand cmd = new SqlCommand(q,conn);
cmd.ExecuteNonQuery();
}
}
}
con.Open() statement generates error..
For SQL Server Connection types please first read this document.
https://www.connectionstrings.com/sql-server/
For your example I think DESKTOP-3N4UH9N is your local PC not the server instance name, isn't it?
Please first find the server instance name by using SQL Server Management Studio (SSMS).
Please try below codes
Standard Security
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Server=myServerAddress; " +
"Database=myDataBase;" +
"User Id=myUsername;" +
"Password=myPassword;"
conn.Open();
Trusted Connection
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Server=myServerAddress;" +
"Database=myDataBase;" +
"Trusted_Connection=True;"
conn.Open();
Connection to a SQL Server instance
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Server=myServerName\myInstanceName;" +
"Database=myDataBase;" +
"User Id=myUsername;" +
"Password=myPassword;"
conn.Open();
Integrated Security
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=MyLocalSqlServerInstance;" +
"Initial Catalog=MyDatabase;" +
"Integrated Security=SSPI;"
conn.Open();
change this
conn.Open();
string q = "Insert INTO ItemType values ('"+ TypeIdTextBox.Text +"'), ('"+ TypeTextBox.Text +"'),('"+ NameTextBox.Text +"')";
SqlCommand cmd = new SqlCommand(q,conn);
cmd.ExecuteNonQuery();
into this
conn.Open();
string q = "Insert INTO ItemType values (#id, #type ,#name)";
SqlCommand cmd = new SqlCommand(q,conn);
cmd.Parameters.AddWithValue("#id", TypeIdTextBox.Text);
cmd.Parameters.AddWithValue("#type", TypeTextBox.Text);
cmd.Parameters.AddWithValue("#name", NameTextBox.Text);
cmd.ExecuteNonQuery();
conn.Close();
make sure the connection can open without any error
<connectionStrings>
<add connectionString="provider=MSDAORA;Data Source=MyOracleDB;User Id=user;Password=****;" name="con"/>
</connectionStrings>
This is my connection string. i am using visual studio 2013 and oracle 10g version.
This is my code.
OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
public DataTable GetTday()
{
conn.Open();
string query = "select * from tday";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
return dt;
}
it shows 'ORA-12154: TNS:could not resolve the connect identifier specified' this error. please someone help
I am struggling with my new website which I recently uploaded on Godaddy server.
Con.open() is the line which is causing error : The wait operation timed out
My Code: file.aspx.cs
SqlConnection con = new SqlConnection(#"Data Source=databaseserverurl;Network Library=DBMSSOCN;Initial Catalog=mydatabase;User ID=something;Password=something;");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (con.State != ConnectionState.Open) {
con.Open();
}
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from mytable";
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
}
For MySQL
You should use MySqlConnection, not SqlConnection.
For SQL Server
Most likely your databaseserverurl is wrong. Make sure your connection string corresponds to the one you have in the control panel. See https://de.godaddy.com/help/find-your-connection-strings-3323.
To ensure, open Sql Server Management Tool (or your favorite sql tool) and login your db with same server, user and password.
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=LENOVO;Initial Catalog=dbMACARON;Integrated Security=True"); SqlCommand com = new SqlCommand("Select * from PRODUCT");
public void Bind()
{
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
con.Open();
com.Connection = con;
com.ExecuteNonQuery();
da.Fill(ds, "PRODUCT");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
com.Connection = con;
SqlDataReader dr;
dr = com.ExecuteReader();
string id = "0";
Source Error:
Line 31: protected void Page_Load(object sender, EventArgs e)
Line 32: {
Line 33: con.Open();
Line 34: com.Connection = con;
Line 35: SqlDataReader dr;
It said error on my con.Open could not open database, what did i go wrong?
sorry im fresh so i need guidance ,
there some source error it tells me
if you are using sql express edition try this:
SqlConnection con = new SqlConnection("Data Source=.\SQLExpress;Initial Catalog=dbMACARON;Integrated Security=True");
Try using port number with the DB server name
What is the authentication mode? Windows Authentication or User id/Password based?
If it is userId/password based, then you need to provide password also.
Try this as it is.
1. Go to Tools menu-> folder option-> view tab and unCheck the following checkbox with name that HIDE EXTENSION FOR KNWON FILE TYPES.
2.Now crate the file as sql with extension udl i.e sql.udl. It will ask you for confirmation press Yes.
Right click on that file and select open with OLEDB CORE DATASERVICE. It will open the dialog box as follows.
![enter image description here][2]
Go to provider tab and select Microsoft OLEDB PROVIDER FOR SQL SERVER.. AND THEN CLICK ON NEXT BUTTON.
Then copy and paste your server name from SQL SERVER MANAGEMENT STUDIO in the first textbox. on second number select which mode you are using and in the end select the database which you want to use from the dropdown.
Click on TEST CONNECTION button it will show you successfull connection .
finally close that window and now open that udl file with notepad. Copy the content starting from the provider name to the end and paste it into your coding page.
Thats it. It will not show you error again.
I HAVE FIX IT MY SELF!! BUT THANKS FOR EVERYONE FOR TRYING HELPING ME OUT !! THANKS YOU!!
what i do is i put double "\" between lenovo and ebg example in sqp connection..
EXAMPLE:
public partial class SignUp : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=LENOVO\EBG; Initial Catalog=dbMACARON; integrated security= True");
SqlCommand com = new SqlCommand("Select * from CUSTOMER");
public void Bind()
{
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
con.Open();
com.Connection = con;
com.ExecuteNonQuery();
da.Fill(ds, "CUSTOMER");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
weird in this web it didt show double "\" in here... but nway thanks.
I'm kind of struggling trying to get this datagrid to bind. Everytime I run my code, I get an error message stating, "Invalid attempt to call Read when reader is closed". I don't see where I am closing my reader. Can you please help me? My code for loading the datagrid is below:
protected void LoadGrid()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["VTC"].ConnectionString;
conn.Open();
string sql = "select * from roi_tracking";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataReader sqlReader = cmd.ExecuteReader())
{
gridROI.DataSource = sqlReader;
gridROI.DataBind();
sqlReader.Dispose();
cmd.Dispose();
}
}
}
}
You can't use a SqlDataReader as a DataSource for a DataGrid.
From MSDN:
A data source must be a collection that implements either the
System.Collections.IEnumerable interface (such as
System.Data.DataView, System.Collections.ArrayList, or
System.Collections.Generic.List(Of T)) or the IListSource interface to
bind to a control derived from the BaseDataList class.
Datasource property:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basedatalist.datasource.aspx
SqlDataReader:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx
A common methodology to bind the query results to your datagrid would be to use a SqlDataAdapter to fill a DataTable or DataSet and then bind that to your DataGrid.DataSource:
protected void LoadGrid()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["VTC"].ConnectionString;
conn.Open();
string sql = "select * from roi_tracking";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill((DataTable)results);
gridROI.DataSource = results;
}
}
}
In addition to what pseudocoder said, you wouldn't want to bind to a SqlDataReader anyway: the connection to the database will remain open so long as the reader instance exists.
You definitely want to deserialize the data into some other disconnected data structure so that you release the connection back into the pool as quickly as possible.