I want to do some sql code run in my webservice in c#
The code is just
[WebMethod]
public void GetCustomers()
{
SqlConnection MyConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Database1.mdf"].ConnectionString);
}
I think I got something wrong in this statement
now my database name is: Database1.mdf
now its table name is: t1
I get an error like
System.NullReferenceException: Object reference not set to an instance
of an object. at WebService1.Service1.GetCustomers() in
C:\Users\PRIYANK\Documents\Visual Studio
2008\Projects\WebService1\WebService1\Service1.asmx.cs:line 36
I don't know what to write in place of [Database1.mdf] so please write what to write in that place.
Here I place some code which might be helpful
[WebMethod]
public void GetCustomers()
{
SqlConnection MyConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Database1"].ConnectionString);
MyConn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "delete from t1 where name='1'";
cmd.ExecuteNonQuery();
}
You aren't supposed to put your data file's name in the ConnectionString[] element place. You should be putting your ConnectionString's name. In other words, look in your config file to where your <connectionStrings> section is. You will see a name=... for a connection string. Use that in your:
ConfigurationManager.ConnectionStrings["YourConnectionStringName"].ConnectionString
Example
Here is a sample from a sample config:
<connectionStrings>
<add name="Sales"
providerName="System.Data.SqlClient"
connectionString= "server=myserver;database=Products;uid=<user name>;pwd=<secure password>" />
</connectionStrings>
If you wanted to create a SqlConnection to the Products database, you would so this:
SqlConnection ProdDb =
new SqlConnection(ConfigurationManager.ConnectionStrings["Sales"].ConnectionString);
Related
I'm trying to connect to a database, but it seems like my connection is not going through. I am using C# MVC for the webpage I'm creating. How can I fix the following error:
System.ArgumentException: 'Keyword not supported: 'metadata'.'.
The error is occuring on the line using (Sqlconnection con = new Sqlconnection(conStr)). What am I doing wrong on this line and is this how you call your SQL query in C# MVC?
string conStr = ConfigurationManager.ConnectionStrings["Training_DatabaseEntities"].ConnectionString;
List<FisYear> YerFis = new List<FisYear>();
using (SqlConnection con = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand("select * from [dbo].[FiscalYear]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
FisYear fy = new FisYear();
fy.FisDate = rdr["ST_FI"].ToString();
YerFis.Add(fy);
}
SelectList list = new SelectList(YerFis, "ST_FI", "FisDate");
ViewBag.DropdownList = list;
}
You're almost certainly trying to use an entity framework connection string to open a connection via new SqlConnection, which won't work.
If you look in your web.config file you'll probably see something similar to:
<connectionStrings>
<add name="Training_DatabaseEntities" connectionString="metadata=res://*/Entity.csdl|res://*.............provider=System.Data.SqlClient;provider connection string=............." />
</connectionStrings>
You could try parsing the connection string by hand to retrieve the bit you actually want, a brief web search suggests that the EntityConnectionStringBuilder may be of use to retrieve it programmatically, here's an example of doing that in a console app:
var connectionString = ConfigurationManager.ConnectionStrings["Training_DatabaseEntities"]
.ConnectionString;
var entityConnectionStringBuilder = new EntityConnectionStringBuilder(connectionString);
var sqlConnectionConnectionString = entityConnectionStringBuilder.ProviderConnectionString;
Console.WriteLine($"EF Connection String: {connectionString}");
Console.WriteLine($"SqlConnection Connection String: {sqlConnectionConnectionString}");
This gives the output (my emphasis):
EF Connection String: metadata=res:///Models.Model1.csdl|res:///Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=cntrra02-sql-rs;initial catalog=Training_Database;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
SqlConnection Connection String: data source=cntrra02-sql-rs;initial catalog=Training_Database;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework
Which shows a connection string that can be passed into a SqlConnection instance.
I am working with asp.net web services using c# need to access the database in web service but getting error in connection string can any one tell me how to specify the connections string of database here..
here is my code here I am using connection string as i use the string in web form..I am beginner so please guide me in step by step manner or reffer any clear and easily understandable manner as I could not get the point how connection sting is being specified in no of tutorials..
[WebMethod(Description = "show student data")]
public DataSet values(int a)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from STUDENT where stdID='"+a+"'", con);
SqlDataReader r;
r = cmd.ExecuteReader();
r.Read();
foreach
return r;
SqlDataAdapter ada = new SqlDataAdapter("Select * from STUDENT where stdID='" + a + "'", con);
DataSet ds = new DataSet();
ada.Fill(ds);
return ds;
}
Here your just to provide name of connection string in .ConnectionStrings[""] bracket and put your connection string in web.config file as per below.
<connectionStrings>
<add name="Dbconnection"
connectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True" ;
providerName="System.Data.SqlClient" />
</connectionStrings>
add this connection string in configuration manager tag in web.config file and write following connection
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString);
add in comment if you need any more help.
Your connection string is a bit wrong... try something like
SqlConnection con = new SqlConnection(
"Data Source=.\\SQLEXPRESS;Initial Catalog=PUTYOURDATABASENAMEHERENOTTHEFILENAME;Integrated Security=True;User ID=YourUserID;Password=YourPassword");
"The User Instance feature is deprecated with SQL Server 2012, use the SQL Server Express LocalDB feature instead." https://www.connectionstrings.com/sql-server/
My connection string, my database, and everything is working just fine, but just when I call it once at my page.
I have several methods that make connection to my database and return a value to me, and for the first time i need to use two of then. And i'm getting this error in conn.Open():
"The ConnectionString property has not been initialized."
"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.InvalidOperationException: The ConnectionString property has not been initialized.
When i call just one is working great.
My source of two of this methods is, i'm using almost the same code for everyone, just changing the table name:
public DataTable Category(){
sda = new SqlDataAdapter("select * from tbl_category", conn);
sda.Fill(dt);
return dt;
}
and
public int CategoryLastId(){
using (conn){
conn.Open();
sqlCommand = new SqlCommand("SELECT MAX(Id) AS LastID FROM tbl_category", conn);
sqlCommand.ExecuteNonQuery();
Int32 newId = (Int32)sqlCommand.ExecuteScalar();
conn.Close();
return Convert.ToInt32(newId);
}
}
feels like they are in conflict(also, calling on .Get with NHibernate, but this also is working fine)
The problem is that the using statement is closing the connection when it returns.
Create the SqlConnection inside your using statement as follows:
using (SqlConnection conn = new SqlConnection(connString)) { ... }
For getting the connection string from your config file:
connString = ConfigurationManager.ConnectionStrings["yourConnString"].ConnectionString;
The configuration file:
<connectionStrings>
<add name="yourConnString" connectionString="..." providerName="..."/>
</connectionStrings>
Change using statement like below. Refer this for more connection strings.
using (SqlConnection conn = new SqlConnection("Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"))
I am developing a Class Library in C# and in this Class Library I am trying to access database through ADO.NET code, But I'm getting this error. I don't know what is the reason behind it. So please tell me how can I solve it.
System.Data.SqlClient.SqlException: An attempt to attach an auto-named database for file C:\Users\vivek.nuna\Documents\VisualStudio2005\Projects\SubsystemSyncService\TestClient\bin\Debug\aspnetdb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
This is the connection string I am using.
<connectionStrings>
<add name="RegistrationConnString"
connectionString="Server=192.168.101.145\SQLEXPRESS;Database=***_HubDB;User Id=sa;Password={C8273EFD-LB2F-4E65-8702-14B61PI08A9}"
providerName="System.Data.SqlClient" />
</connectionStrings>
Note: I can't see a file aspnetdb.mdf in the Debug folder.
This is the code, how I am using ado.net code.
private DataSet GetAddressFieldsAccordingtoAddressId(string strAddressId)
{
try
{
strConnString = ConfigurationManager.ConnectionStrings["RegistrationConnString"].ToString();
SqlConnection connection = new SqlConnection(strConnString);
SqlCommand command = new SqlCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "[dbo].[PL_spPLUIGetAddressFieldsAccordingtoAddressId]";
command.Parameters.Add("#lAddressID", System.Data.SqlDbType.Int).Value = Convert.ToInt32(strAddressId);
command.Connection = connection;
DataSet dsPwd = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter(command);
dAdapter.Fill(dsPwd);
command.Dispose();
dAdapter.Dispose();
return dsPwd;
}
catch (Exception ex)
{
return null;
}
}
I have added reference of this class Library in a C# form.
C# form is calling this method of class library.
If you want a standalone database for your application, you should have a look at
SQL Server Compact : http://www.microsoft.com/sqlserver/2008/en/us/compact.aspx
SQLite : http://sqlite.phxsoftware.com/
For connectionstrings see http://www.connectionstrings.com/access-2003/.
SqlCeConnection sqlConnection1 = new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = C:\\Users\\Administrator\\My Documents\\BMS_Data.sdf;Persist Security Info=False";
I am currently trying to establish a connection between an ASP.NET web site project and a Database built by SQL Server 2008 R2.
The way I am required to do so is to use the connectionString from the Web.config page, but I have no idea what value to give it or how to establish a connection using said value. (Using C#)
Any help would be appreciated, as I found next to no information about the subject.
Here is the (default) value that is currently in the Web.config page:
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
Use Configuration Manager:
using System.Data.SqlClient;
using System.Configuration;
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
using(SqlConnection SqlConnection = new SqlConnection(connectionString));
//The rest is here to show you how this connection would be used. But the code above this comment is all you really asked for, which is how to connect.
{
SqlDataAdapter SqlDataAdapter = new SqlDataAdapter();
SqlCommand SqlCommand = new SqlCommand();
SqlConnection.Open();
SqlCommand.CommandText = "select * from table";
SqlCommand.Connection = SqlConnection;
SqlDataReader dr = SqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
This article about Connect to SQL Server Using SQL Authentication in ASP.NET will probably give you a better idea of what need to be done.
As a pre check, just check if your mssqlserver services are running.
string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = commandText;
// command.Parameters.AddWithValue("#param", value);
connection.Open();
command.ExecuteNonQuery(); // or command.ExecuteScalar() or command.ExecuteRader()
}