ALTER DB error when the connection string has an instance name - C# 4.0 - sql

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"

Related

Select and Update accdb database in ASP.net

I am able to select information from my database and retrieve information, but why cant i use the same to update the database?
Commandstring is what i use to write my SQL Sentences.
Not Working:
DatabaseConnection.Commandstring = ("UPDATE tbl_login SET Time='"+Settings.UpdateRecord+"' WHERE Username='"+Settings.LoginName+"' ");
Connection code:
public static string ConString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + System.Web.HttpContext.Current.Server.MapPath("MainData.accdb") + "'; Persist Security Info = False;";
public static string Commandstring;
public static object result;
public static void Connect() {
using (OleDbConnection con = new OleDbConnection(DatabaseConnection.ConString)) {
con.Open();
Debug.WriteLine("Connection to DB Established");
using (OleDbCommand cmd = new OleDbCommand(Commandstring, con)) {
try {
cmd.ExecuteNonQuery();
con.Close();
Debug.WriteLine("Connection to DB Terminated");
}
catch (Exception ex) {
Debug.WriteLine("Error Updating Database: " +ex.Message);
con.Close();
}
}
}
}
}
my exception message is saying there is an Syntax error in my Update statement.
Sending the statement to Debug writeline i get:
UPDATE tbl_login SET Time='21' WHERE Username='Bob'
Time is a reserved word. Enclose it in square brackets like this:
UPDATE tbl_login SET [Time]='21' WHERE Username='Bob'
I also think you should switch to a parameter query. But the reserved word issue is the cause of your immediate problem, and will also be an issue in a parameter query.

Connecting to SQL Server database no opening MVC 4

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;

how to insert row in SQL database in ADO.Net Connection oriented mode

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();
}

Get last replication date/time from SQL server CE

I have a Windows Mobile 6.0 application with SQL Server CE 3.5 on the device. The program gets the latest data from the publisher - SQL Server 2008. The replication is working fine but I want to display to the user the last time it replicated from the server.
Does anyone know where I can get the SQL that I can execute on the device to get this information from the SQL Server CE?
All help greatly appreciated.
Mike
/// <summary>
/// Get the local Datetime for last succesful synchronization
/// If no Synchronization has happened, will return DateTime.MinValue
/// </summary>
/// <param name="connection">An open connection to the local database</param>
/// <returns>The date and time for the last succesful sync</returns>
public DateTime GetLastSuccessfulSyncTime(SqlCeConnection connection)
{
if (!System.IO.File.Exists(connection.Database))
return DateTime.MinValue;
if (connection.State != System.Data.ConnectionState.Open)
{
connection.Open();
}
var props = GetPropertiesFromSettings();
using (SqlCeCommand cmd = connection.CreateCommand())
{
cmd.Connection = connection;
cmd.CommandText = "SELECT table_name FROM information_schema.tables WHERE TABLE_NAME = #table";
cmd.Parameters.Add("#table", SqlDbType.NVarChar, 4000);
cmd.Parameters["#table"].Value = "__sysMergeSubscriptions";
object obj = cmd.ExecuteScalar();
if (obj == null)
return DateTime.MinValue;
cmd.Parameters.Clear();
cmd.CommandText = "SELECT LastSuccessfulSync FROM __sysMergeSubscriptions " +
"WHERE Publisher=#publisher AND PublisherDatabase=#database AND Publication=#publication";
cmd.Parameters.Add("#publisher", SqlDbType.NVarChar, 4000);
cmd.Parameters["#publisher"].Value = props.Publisher;
cmd.Parameters.Add("#database", SqlDbType.NVarChar, 4000);
cmd.Parameters["#database"].Value = props.PublisherDatabase;
cmd.Parameters.Add("#publication", SqlDbType.NVarChar, 4000);
cmd.Parameters["#publication"].Value = props.Publication;
obj = cmd.ExecuteScalar();
if (obj == null)
return DateTime.MinValue;
else
return ((DateTime)obj);
}
}

Foxpro: Check whether table exists via vfpoledb

I access data in .dbf files via System.Data.OleDb (vfpoledb.dll). How can I find out whether table exists via SQL command? Something similar to the following on SQL server:
IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END
If you have a dbc file you can query it to see if the table exists.
string dbc = "northwind.dbc";
using (OleDbConnection conn = new OleDbConnection(connectionString)) {
DataTable dt = new DataTable();
string sql = string.Format(#"SELECT * FROM {0} WHERE ALLTRIM(ObjectType) = 'Table' AND UPPER(ALLTRIM(ObjectName)) = '{1}'", dbc, tableName.ToUpper());
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
da.Fill(dt);
bool tableExists = dt != null && dt.Rows.Count == 1;
}
But really you don't need a sql command or a dbc file to get that information. You can get it straight from the OleDbConnection using the GetSchema method.
using (OleDbConnection conn = new OleDbConnection(connectionString)) {
conn.Open();
DataTable tables = conn.GetSchema("Tables");
conn.Close();
var tableExists = (from row in tables.AsEnumerable()
where row.Field<string>("Table_Name").Equals(tableName, StringComparison.CurrentCultureIgnoreCase)
select row.Field<string>("Table_Name")).FirstOrDefault() != null;
}
Additionally, if you are connecting to DBF tables that are "FREE" tables and NOT actually part of a connected "database" (.dbc), then you can just check for the file's existence or not... Such as in C# via
if( File.Exists( PathToTheDatabaseDirectory + TableYouExpect + ".DBF" ))
file is there
else
file is missing
I don't know how to do it only using SQL but maybe you could check for the existence of the file on disk using the File.Exists Method or you could write some code to check for the existence of the dbf using the OleDb classes:
private bool DbfExists(string dbfName, string connectionString)
{
bool dbfExists = true;
using(OleDbConnection conn = new OleDbConnection(connectionString))
{
string sql = string.Format("SELECT * FROM {0}", dbfName);
using(OleDbCommand command = new OleDbCommand(sql, conn))
{
OleDbDataReader reader = null;
try
{
conn.Open();
reader = command.ExecuteReader();
}
catch(Exception ex)
{
dbfExists = false;
}
finally
{
conn.Close();
reader = null;
}
}
}
return dbfExists;
}
I have not tried compiling this code so it may need to be tweaked a bit.