Filepath changing while executing sql query from c# - c#

I have a sql database where i am string filepath and file name of some files. I am using Visual Studio 2008 as IDE and SQL Server 2005 for development.
If I am trying to execute a SQL query to get filepath it returns correct result. But when I am executing SQL query from windows application in c#, it is returning Filepath in which all \ are changed to //.
Here is the SQL query I executed from SQL Server Management Studio:
select FilePath FROM dbo.[tbl_name] WHERE SerialNo = 2;
It results in FilePath being C:\Program Files\Test\Mydoc.pdf
But when I am trying through C# windows forms code as mentioned below. I am getting a wrong value for FilePath: C://Program Files//Test//Mydoc.pdf
try
{
using (connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT FilePath FROM dbo.[tbl_name] WHERE SerialNo LIKE #Sno", connection))
{
command.Parameters.Add(new SqlParameter("Sno", Serial));
FiletoOpen = command.ExecuteScalar().ToString();
Process.Start(FiletoOpen );
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Exception has occured!", MessageBoxButtons.OK);
}
finally
{
connection.Close ();
}
What may be the problem?

I guess you are seeing this path in your debugger. Debugger is just escaping the path and nothing else. If you write it somewhere, like console, you will get the original path (with single backslashes).

Related

failed to connect to database using c#

I want to ask about connecting db with c#.
I have read http://csharp.net-informations.com/data-providers/csharp-sql-server-connection.htm and written my code, but the connection doesn't seem to be working.
This is my code:
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=localhost;Initial Catalog=dbabc;User ID=admin;Password=qwerty";
sql = "UPDATE ppd,brg,cmp SET WHERE";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
MessageBox.Show(dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + " - " + dataReader.GetValue(2));
}
dataReader.Close();
command.Dispose();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Did I write something wrong? The error message shown always says "Can not open connection"!
The Exception thrown should be a SqlException. Check the ErrorCode on the SqlException and look it up here...
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-develop-error-messages
Rather than catch(Exception ex) your code should do this...
try
{
connection.Open();
....
connection.Close();
}
catch (SqlException ex)
{
MessageBox.Show($"Can not open connection ! ErrorCode: {ex.ErrorCode} Error: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Can not open connection ! Error: {ex.Message}");
}
I think you should check server name
if you install SQL server (Standard) on your computer, server name named is (local) or .
If you are using VS create a data source and test the connection string. Go to data> Add new data source. There is find your database server and create the correct string.
Your code is working. I can verify it. Please check your connection string and SQL query. Especially your SQL query. It seems to be wrong.
Try to execute the query in Microsoft SQL Server Management Studio. If there is an error in your query, you can easily find it there.
SQL Update Syntax
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Recommended Readings
https://www.tutorialspoint.com/sql/sql-update-query.htm
https://www.w3schools.com/sql/sql_update.asp
To verify the connection string,
Open the Server Explorer pane. ("View" menu, "Server Explorer" or
use the key shortcut CTRL+Alt+S).
Right-click on the Data Connections, Select Add connection and then
press continue after selecting Microsft SQL Server as the Data source.
Select Refresh and click down arrow and then select your SQL server.
If you cannot find it, enter the server name manually.
You may also have to enter the SQL server credentials.
Select or enter your database name & then press Test Connection.
If you see a Test connection succeeded message, then your SQL server is working.
If you want, you can also get connection string by pressing Advanced.. button and then copying the connection string
In addition, try to an add exception message to catch block. That way, you can easily find the error.
MessageBox.Show("Can not open connection ! \n" + ex.Message);

Restore MSSQL database on remote machine from backup file via C# code

I have a mssql database on remote machine and backup file for this database. I want to create a method (c#) for restoring of database from backup. I will execute my method on my local machine. Can somebody help me to create such method for restoring remote database?
Try the this:
public void RestoreDatabase(string fileName)
{
try
{
using (SqlConnection conn = new SqlConnection("connectionString"))
{
string sql = "RESTORE DATABASE YourDatabase FROM DISK = N''" + fileName;
conn.Open();
SqlCommand _command = new SqlCommand(sql, conn);
_command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw;
}
}
You call it this way :
RestoreDatabase(#"\\remotemachine\...\YourFile.bak");
NB: Put an actual path for where the file is located

Can't use sql server ce 4.0 in asp.net in visual studio 2012

At first it wrote this exception:
"SQL Server Compact is not intended for ASP.NET development."
and then I added:
AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);
to the Global.aspx and it fixed it.
But now when I try to open the SqlCeConnection it gives me this exception:
Incompatible Database Version. If this was a compatible file, run
repair. For other cases refer to documentation. [ Db version =
4000000,Requested version = 3505053,File name =
\?\C:\Users\gal\Documents\Visual Studio
2012\WebSites\Project_Level_4\DB\PhoneBookWeb.sdf ]
Can anyone please help ?
Install the SQL CE 4.0 package: http://www.microsoft.com/en-us/download/details.aspx?id=17876
Try adding the reference in your IDE to "C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Desktop\System.Data.SqlServerCe.dll"
Add the using clauses:
using System.Data.SqlServerCe;
using System.IO;
Then try something like this:
string connectionString;
string fileName = "test.sdf";
string password = "test";
if (File.Exists(fileName))
File.Delete(fileName);
connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", fileName, password);
SqlCeConnection conn = null;
try {
SqlCeEngine engine = new SqlCeEngine(connectionString);
engine.CreateDatabase();
conn = new SqlCeConnection(connectionString);
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "CREATE TABLE myTable (col1 int, col2 ntext)";
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally {
conn.Close();
}

Executing SQL scripts with GO statements without SMO

One thing I’m having problems with, is deploying app to machine not having SMO installed on it. I want to execute scripts having GOstatements, but also would like to avoid the need for installing SMO package on a target machine or parsing SQL script file (since I don't know if sql script will contain functions or SPs).
I tried manually copying SMO relevenat dlls to bin folder of executable but there are always some other dlls needed to run the app.
Any help with this?
Alternatively to SMO, the sqlcmd utility can understand GO statements. You will need to use System.Diagnostics.Process in order to call out to it with your script as an argument.
By no means am I saying this is the way to do it, but it is a valid alternative. You still have the same issues as before if the utility doesn't exist on the target machine.
You might also be able to deploy SMO with the installer package without "installing" it on the target machine:
Embedding SMO dlls in Setup and deployment
I find below solution well tested
using (SqlConnection cn = new SqlConnection(connectionString))
{
try
{
cn.Open();
FileInfo file = new FileInfo(fileName);
string script = file.OpenText().ReadToEnd();
string[] splitChar = { "\r\nGO\r\n" };
var sqlLines = script.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);
int res = 0;
SqlCommand cmd = null;
foreach (var query in sqlLines)
{
cmd = new SqlCommand(query, cn)
{
CommandTimeout = 5400
};
res = cmd.ExecuteNonQuery();
}
cn.Close();
}
catch (Exception ex)
{
msg = ex.Message;
}
finally
{
cn.Close();
}
}

Is it possible to output the results of an sql command to a text file, when sent via SMO in C#?

I am using SMO in C# to run an SQL script. I need to output the results of the file into a text file.
When using a command line to run the query I can get the desired result using the "-o [output file]" argument. Is there a way to carry out the same operation using an SMO object?
At the moment my code simply sends an sql script to a server:
// Read the sql file
string script = sqlFile.OpenText().ReadToEnd();
// Create a new sql connection, and parse this into a server connection.
SqlConnection sqlConnection = new SqlConnection(connectionString);
Server server = new Server(new ServerConnection(sqlConnection));
// Run the sql command.
server.ConnectionContext.ExecuteNonQuery(script);
Any help would be much appreciated!
I don't know if you can do the exact same thing, but assuming that the script returns some data you could just execute the script, read the returned data and store it to a file, for example:
using (StreamWriter sw = new StreamWriter("output.txt"))
{
using(SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using(SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = script;
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
sw.WriteLine(rdr.Item("colName").ToString();
}
}
}
}
}
Discovered that the SQL script that I needed to execute basically only outputted errors it encountered into the output file. I was able to catch this using:
catch (Exception ex)
{
executedSuccessfully = false;
SqlException sqlex = ex.InnerException as SqlException;
if (sqlex != null)
{
exceptionText = sqlex.Message;
}
}
Thanks for your help though Ho! I may need this in the future...

Categories