'SqlConnection' is not declared error for aspx net - asp.net

I am fairly new to this Aspx.Net. I am trying to connect to a remote SQL Server and below is the connection string I am trying on IIS server.
SQL Server version is 2012
MySqlConnection connection = new MySqlConnection("Database=DB;Server=server.name;Uid=user.name;Pwd=pass");
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "select * from dbo.TableName";
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//reader.GetString(0)
//reader["column_name"].ToString()
}
reader.Close();
Below is the error:
Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: BC30451: Name 'SqlConnection' is not declared.
Appreciate any help, please keep in mind this is my first tries out on aspx. Yes, I tried searching online but can't seem to find a resolution.

Well, if you want to use SQL Server in C#, try follow below technique:
SqlConnection sqlConn = new SqlConnection("Server=server.name;Database=DB;User Id=userid;Password=yourpass;");
SqlCommand cmd = new SqlCommand("select * from dbo.TableName", sqlConn);
sqlConn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
//reader.GetString(0)
//reader["column_name"].ToString()
}
reader.Close();
sqlConn.Close();

Related

SQL Server stored procedure in asp.net core

I created the application in ASP.NET core which needs to get details from SQL Server through a stored procedure.
Here is my code
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#lat", "31.77987");
cmd.Parameters.AddWithValue("#lng", "-106.4119");
cmd.Connection = connection;
cmd.CommandText = "sp_Procedure";
var r = cmd.ExecuteNonQuery();
When I run this code, I got an error
The server is attempting to use a feature that is not supported on this platform
If I missed out anything please correct me.

Unable to update database with the Window Form Application

I am trying to update my database with the window form I have created, however an error occurred when I execute the code:
An unhandled exception of type 'System.InvalidOperationException'
occurred in System.Data.dll" at comm.ExecuteNonQuery();
Here is the code that I used to connect to my database. Was the code I used to update the database wrong?
string conn=ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
SqlCommand comm = new SqlCommand("UPDATE ExerciseInstruction SET Accumulated_Daily_Sets_Completed = '0' WHERE ExerciseInstructionsID ='" + exerciseInstructionID +"'", connection);
comm.ExecuteNonQuery();
Here is the complete error message :
ExecuteNonQuery requires an open and available Connection. The
connection's current state is closed.
The error message explain all. The command cannot be executed if the code doesn't know how to reach the database. Just a call to connection.Open should fix the problem, however I think you need to use a proper way to execute the query.
This is called Parameterized query. In this way you don't concatenate strings together to form you query text but use parameters to pass values to the database engine and a special formatted string containing the parameters placeholders.
There are two main advantages to do so. It is not possible to target your code with Sql Injection hacks and you don't have to handle quoting around your strings (an infinite source of bugs)
string conn=ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
string cmdText = #"UPDATE ExerciseInstruction
SET Accumulated_Daily_Sets_Completed = 0
WHERE ExerciseInstructionsID =#exid";
using(SqlConnection connection = new SqlConnection(conn))
using(SqlCommand comm = new SqlCommand(cmdText, connection))
{
connection.Open(); // Need this before executing the query
comm.Parameters.Add("#exid", SqlDbType.Int).Value = exerciseInstructionID;
comm.ExecuteNonQuery();
}

How to set database with AdomdConnection

When I execute this code:
AdomdConnection con = new AdomdConnection("Data Source=MyServer;User ID=MyDomain\\MyUserName;Password=MyPassword");
con.Open();
con.ChangeDatabase("Analysis Services Project1");
I get this exception:
Either the user, MyDomain\MyUserName$, does not have access to the
Analysis Services Project1 database, or the database does not exist.
The database name comes from looking at the server using Microsoft SQL Server Management Studio. If I bring up the properties on the server and go to the security section, my account is listed as a Server administrator. While in management studio, I can see data sources, cubes and execute mdx queries fine.
Why can't do I get this exception in code?
whihc line causes the error?
I imagine you have to infor the catalog on your connection string. Try addind
Catalog=Analysis Services Project1
to your con string.
Also, Analysis Services Project1 seems to be the projects name? Are you sure this is the database name as well?
First
added the reference for Microsoft.AnalysisServices.AdomdClient.dll
strCon = "Data Source=DBserverServerName;Integrated Security=SSPI;Initial Catalog=DBName;";
AdomdConnection con = new AdomdConnection("connectionstring"); // connect DB con.Open(); AdomdCommand cmd = new AdomdCommand("MDX query", con); //query
AdomdDataReader reader = cmd.ExecuteReader(); //Execute query
while (reader.Read()) // read
{
Data dt = new Data(); // custom class
dt.Gender = reader[0].ToString();
dt.Eid = reader[1].ToString();
dt.salary = reader[2].ToString();
data.Add(dt);
}

COM Interop Exception when trying to read Excel file ASP.net

I have a very simple ASP.net 4.0 application that lets users read data from a common Excel file. The Excel file is situated within the application itself i.e. it rests on the server side in a folder right below the root.
I'm populating a Dataset with the Excel data using this code:
public DataTable GetExcelData(string ExcelFilePath)
{
DataTable dt = new DataTable();
string OledbConnectionString = string.Empty;
OleDbConnection objConn = null;
OledbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";
objConn = new OleDbConnection(OledbConnectionString);
if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
string resName = "'";
string depName = department;
resName += userLastName + ", " + userFirstName + "'";
OleDbCommand objCmdSelect = new OleDbCommand("Select * from [" + depName + "$A3:Q10000] where Resource=" + resName, objConn);
OleDbDataAdapter objAdapter = new OleDbDataAdapter();
objAdapter.SelectCommand = objCmdSelect;
DataSet objDataset = new DataSet();
objAdapter.Fill(objDataset, "ExcelDataTable");
dt = objDataset.Tables[0];
addSumRow(dt);
objConn.Close();
return objDataset.Tables[0];
}
and after this I attache the Dataset to a Gridview and that's about it.
Now when I run the app on my local host there's no problem showing the Excel data, however, after deployment to our web server the application fails with this error:
The specified domain either does not exist or could not be contacted.
Description: An unhandled exception occurred during the execution of the current web >request. Please review the stack trace for more information about the error and where it >originated in the code.
Exception Details: System.Runtime.InteropServices.COMException: The specified domain >either does not exist or could not be contacted.
Source Error:
An unhandled exception was generated during the execution of the current web request. >Information regarding the origin and location of the exception can be identified using >the exception stack trace below.
Any help is very much appreciated!
Thanks!
few thing you may try
1>Disable anonymous access and enable identity impersonation
2>Ensure Excel file path is correct

error in mysql connection "The given key was not present in the dictionary"

I have problem while connecting to mysql database using "ADO.NET Driver for MySQL (Connector/NET)"
I got this exception The given key was not present in the dictionary.
Edit:
MySqlConnection con = new MySqlConnection("Server=localhost;Database=pgs_db;Uid=root;Pwd=;");
MySqlCommand com = new MySqlCommand();
com.CommandType = CommandType.StoredProcedure;
com.Connection = con;
com.CommandText = "getStudent";
con.Open();
MySqlDataReader dr =com.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();
sorry i was using a worng connectionstring
this is a right one :
"server=localhost; user id=user; password=password; database=mydatabase; pooling=false;"
thnx Oded
Without seeing the code, I am guessing you are trying to access a configuration key that does not exist in your application config file.
Edit:
After seeing the code sample, the problem is probably not with connecting to the DB.
I would say that in your GridView, you are binding to a field that is not returned by the DB query.

Resources