I am having trouble connecting to my database to run a query. Here us the connection and query info:
string connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\\Webs\\MvcFFL\\MvcFFL\\App_Data\\Players.mdf;Integrated Security=True";
string queryString = "Truncate table Players;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open(); <- Fails here opening the connection
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
Can someone explain why this is failing to open the connection. This is using SQL Server. I have this declared at the top:
using System.Data.SqlClient;
Related
I'm creating a new webservice in ASP.NET 5 using the new .NET Core library, so far I've only hit an issue with using DataSet and DataTable.
According to this site they are not included at this moment in time, which is fine, but I don't know what alternatives I have at this time, so I'm just looking for some guidance.
I have the following code:
public string Get(string p_sUserId, string p_sUserPassword, int p_iCustId)
{
Select qrySelect = new Select();
using (SqlConnection conn = new SqlConnection(Startup.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(qrySelect.getData(), conn))
{
cmd.Parameters.AddWithValue("#Id", sTestId);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataSet ds = new DataSet())
{
// foo
// bar
}
}
}
}
return "value";
}
How should I handle the data that is being return from the query? I need to build and return a string using the above data fetched from the query. Any help and guidance would be appreciated.
I believe SqlDataReader should work.
string sql = "SELECT * FROM Table";
using (SqlConnection con = new SqlConnection(Startup.ConnectionString)) {
con.Open();
using (SqlCommand command = new SqlCommand(sql, con)) {
using (IDataReader dr = command.ExecuteReader()) {
while (dr.Read()) {
//process data
}
}
}
}
DataTable and SqlDBAdapter are now supported using .NET Standard 2.0. Upgrade to VS2017 Preview, add System.Data.Common and System.Data.SqlClient nugets, and the code below should work. More detail at the blog post here -> https://blogs.msdn.microsoft.com/devfish/2017/05/15/exploring-datatable-and-sqldbadapter-in-asp-net-core-2-0/ . GitHub repo here -> https://github.com/jhealy/aspdotnetcore/tree/master/SqlClientPlay20 .
public static DataTable ExecuteDataTableSqlDA(SqlConnection conn, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
System.Data.DataTable dt = new DataTable();
System.Data.SqlClient.SqlDataAdapter da = new SqlDataAdapter(cmdText, conn);
da.Fill(dt);
return dt;
}
I am using ASP.Net WebserviceApplication for my application and it is communicating with my SQL Server. Should I close SQLConnection after all user's sql transactions or it should be open everytime?
For example;
public void Connection()
{
if (connection == null)
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString());
if (connection.State == ConnectionState.Closed)
connection.Open();
else if (connection.State == ConnectionState.Broken)
{
connection.Close();
connection.Open();
}
}
[WebMethod]
public long GetUsersRankMonthly(string userName)
{
Connection();
SqlCommand command = new SqlCommand("Select scores.Rank From (SELECT ROW_NUMBER() OVER(ORDER BY Score DESC) AS Rank,Score,NickName,ID FROM teatalay.TopScoresGeneral) scores Where UserName = #userName", connection);
command.Parameters.Add(new SqlParameter("#userName", userName));
var result = (long?)command.ExecuteScalar();
return result.HasValue ? result.Value : -1;
}
Thank you.
Wrap your transactions in a using statement when using a sql command. Let ASP.NET take care of SQL Connection pooling. It is a bit more refined at it than your code. Keep everything as condensed as possible and only modify if you notice that the number of connections to your server are what are the source of your performance issues.
Edit
using (var cnn = new SqlConnection("connection string here")){
using (var cmd = new SqlCommand("SProc or parametized text", cnn)){
cnn.Open();
// do stuff
cnn.Close();
}
}
In general when handling connections is better to use using moreover the block
if (connection.State == ConnectionState.Closed)
doesn't guarranty that it will open you the connection because you might be at ConnectionState.Connecting
The using statement guarantes it will close you connection when finished:
public long GetUsersRankMonthly(string userName)
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString());
using (connenction)
{
connenction.Open();
SqlCommand command = new SqlCommand("Select scores.Rank From (SELECT ROW_NUMBER() OVER(ORDER BY Score DESC) AS Rank,Score,NickName,ID FROM teatalay.TopScoresGeneral) scores Where UserName = #userName", connection);
using (command)
{
..........
......
}
}
}
I want to run a SQL Query like
SELECT a,b,c,d FROM table1 WHERE userID.table1 = userID.table2
I want the output to go to the a DataGrid.
I am using SQL Server 2012.
This is a Silverlight 5 application using the "Business Application" template.
Here is my code from my C# WinForm App. I am trying to port to Silverlight
public SqlConnection ConnectionStateToSQLServer()
{
//string source = "Data Source=.;Initial Catalog=catalog_skull_primary;Integrated Security=SSPI;";
//databaseConnectionstring = source;
try
{
SqlConnection conn = new SqlConnection(databaseConnectionstring);
conn.Open();
//MessageBox.Show("Connection Test Successful");
connection = conn;
conn.Close();
return conn;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
//MessageBox.Show(e.ToString());
}
return null;
}
I have a database in which a table has name Registration which is used to register the user.
It has only two column one is Username and one is password.
A page named Register.aspx is used for registering the member which have two textbox one is for taking Username(textbox1) and one is for taking password(textbox2) and one button for insert these value in database.
The Main problem is that we cannot write statement like this :
Insert into Registration (Username, password)
values ('TextBox1.text','TextBox2.text')
I am using ADO.net Connection oriented mode, I googled but I didn't find any way to insert row in SQL database in connected mode. Please provide me a idea for inserting this row?
ADO.NET has DataReader which supports Connected mode. All else are disconnected.
DataReader is connected architecture since it keeps conneection open untill all records are fetched
If you want to insert in ADO.NET then you should perform the following steps:
private void btnadd_Click(object sender, EventArgs e)
{
try
{
//create object of Connection Class..................
SqlConnection con = new SqlConnection();
// Set Connection String property of Connection object..................
con.ConnectionString = "Data Source=KUSH-PC;Initial Catalog=test;Integrated Security=True";
// Open Connection..................
con.Open();
//Create object of Command Class................
SqlCommand cmd = new SqlCommand();
//set Connection Property of Command object.............
cmd.Connection = con;
//Set Command type of command object
//1.StoredProcedure
//2.TableDirect
//3.Text (By Default)
cmd.CommandType = CommandType.Text;
//Set Command text Property of command object.........
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
//Assign values as `parameter`. It avoids `SQL Injection`
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
Execute command by calling following method................
1.ExecuteNonQuery()
This is used for insert,delete,update command...........
2.ExecuteScalar()
This returns a single value .........(used only for select command)
3.ExecuteReader()
Return one or more than one record.
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
try
{
using (var connection = new SqlConnection(yourConnectionString))
{
string queryString = "Select id, name, age from Table where name = #name";
using (var command = new SqlCommand(queryString, Connection))
{
command.Parameters.AddWithValue("#name", name);
Connection.Open();
SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
item = new Item(long.Parse(dataReader[0].ToString()),
dataReader[1].ToString(),
int.Parse(dataReader[2].ToString()));
}
dataReader.Close();
}
}
}
catch (Exception ex)
{
// if exception will happen in constructor of SqlConnection or Command, the // resource can leak but Dispose method will never be called, couse the object was not created yet.
// Trace and handle here
throw;
}
finally
{
}
But ADO.net is useless for enterprice development. You have to have and abstraction from Data Acess Layer and go to entities, not table records
Use the ORM, Luke!
using System.Data.SqlClient;
string cnstr = "server=.;database=dbname;user=username;password=password;";
SqlConnection con = new SqlConnection(cnstr);
SqlCommand cmd = new SqlCommand { Connection = con };
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
//something;
}
finally
{
if (con != null)
con.Close();
}
I have a service written in C# that runs under the domain admin account. This account is set as SQL admin on all the SQL Servers in that domain. The service needs to copy a mdf/ldf (SQL server 2003 or 2008) from one server to another and attach it to the new server. Instead of detaching the DB at the source server, I am changing the DB status to read only, and then copying the mdf/ldf files. Once they get copied over, I reset the DB status to read-write.
This is working if the source server name is something like MYSQLSERVER2K8. However, the code does not work if it is an instance name. For example: MYSQLSERVER2K8\VAULT. I have run the unit tests in NUnit on my code and the unit tests pass for both cases. However, the service is unable to change the DB status. The error we get is as follows:
SQL: ALTER DATABASE My_Test_DataBase SET SINGLE_USER WITH ROLLBACK IMMEDIATE ---> System.Data.SqlClient.SqlException: Database 'My_Test_DataBase' does not exist. Check sysdatabases. ALTER DATABASE statement failed. at System.Data.SqlClient.SqlConnection.
Here is my code (note that I am converting the server name to the IP address in the connection string. For example: MYSQLSERVER2K8\VAULT gets converted to 111.111.111.111\VAULT:
#region ChangeDatabaseStatus
/// <summary>
/// Change the database status to read-only/read-write
/// </summary>
/// <param name="serverName"></param>
/// <param name="databaseName"></param>
/// <param name="status"></param>
public virtual bool ChangeDatabaseStatus(string serverName, string databaseName, string status)
{
DateTime beginTimeStamp = DateTime.Now;
string sql = String.Empty;
bool databaseStatusChanged = false;
try
{
SqlConnection connection = GetSqlConnection(false);
string connectionString = connection.ConnectionString;
string serverIPAddress = Dns.GetHostAddresses(serverName.Contains(#"\") ? serverName.Substring(0, serverName.IndexOf(#"\")) : serverName)[0].ToString();
connectionString = connectionString.Replace("{0}", serverIPAddress = serverName.Contains(#"\") ? serverIPAddress + serverName.Substring(serverName.IndexOf(#"\"), serverName.Length - serverName.IndexOf(#"\")) : serverIPAddress);
connection.Close();
connection = new SqlConnection(connectionString);
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandTimeout = _commandTimeout;
command.CommandType = CommandType.Text;
command.CommandText = String.Format("ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE", databaseName);
//Debugging & Exception handling
sql = HelperFunctions.BuildSQL(command);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandTimeout = _commandTimeout;
command.CommandType = CommandType.Text;
command.CommandText = status == "ReadOnly" ? String.Format("ALTER DATABASE {0} SET READ_ONLY", databaseName) : String.Format("ALTER DATABASE {0} SET READ_WRITE", databaseName);
//Debugging & Exception handling
sql = HelperFunctions.BuildSQL(command);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
databaseStatusChanged = true;
}
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandTimeout = _commandTimeout;
command.CommandType = CommandType.Text;
command.CommandText = String.Format("ALTER DATABASE {0} SET MULTI_USER", databaseName);
//Debugging & Exception handling
sql = HelperFunctions.BuildSQL(command);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
catch (Exception e)
{
throw new DataProviderException(String.Format("{0} operation failed. SQL: {1}", MethodBase.GetCurrentMethod().Name, sql), e);
}
finally
{
LogPerformance(String.Format("Elapsed time for: {0}", MethodBase.GetCurrentMethod().Name), beginTimeStamp, DateTime.Now, null);
}
return databaseStatusChanged;
}
#endregion //ChangeDatabaseStatus
Check you don't have an alias configured.
Load the Sql Server Configuration Manager, under Native Client, then Aliases.
As Tony Hopkinson says, test you can connect using sqlcmd or something from the same machine:
sqlcmd -S MYSQLSERVER2K8\VAULT -q "ALTER DATABASE dbname SET SINGLE_USER WITH ROLLBACK IMMEDIATE"