Open MSQL procedure from C# application (using System.Diagnostics) - c#

I am having difficulties in finding a solution for opening a stored procedure straight to MSQL management studio for modifying in a new SQLQuery from my C# application (winform).
Here is my code:
Process openSQL = new Process();
openSQL.StartInfo.FileName = "Ssms.exe";
openSQL.StartInfo.Arguments = "dbo.getResults"; //name of the stored procedure I want to open
openSQL.Start();
I am getting error after executing the code :"The following files were specified on the command line: dbo.getResults These files could not be found and will not be loaded."
How am I supposed to "point" to the stored procedure in C# and get its definition displayed and ready to get modifications in MSQL management studio?

This isn't possible I'm afraid. If you run ssms -? from the command line you can see all the parameters that you can pass in:
Some options:
Let users edit procs themselves. After all, anyone capable of doing this will understand how to use SSMS properly.
Make your own UI. You can read the contents of a stored procedure and display them in a text box. The downside is that you lose features such as syntax highlighting (unless you also build that in too)
You could download the procedure and store it in a procedure.sql file and get SSMS to open that. Don't forget to pass in the server, database and credentials.

I found a way to open a stored procedure script straight to MSQL management studio for modifying in a new SQLQuery from my C# application (winform).
I am taking the script of the procedure with EXEC sp_helptext 'procedure_name'
The result set is filled in a DataSet
And the DataSet is getting written in an empty .sql file
The .sql file is getting opened in MSQL Managment Studio with System.Diagnostics;
Here are the steps with code snippets:
private void saveProcToAFile()
{
StreamWriter log;
if (!File.Exists("procedureToBeLoaded.sql"))
{
log = new StreamWriter("procedureToBeLoaded.sql");
}
else
{
log = new StreamWriter(File.Create("procedureToBeLoaded.sql"));
}
SqlConnection conn = new SqlConnection(conString);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = string.Format("EXEC sp_helptext '{0}'", "procedure_name"); //Step 1.
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds); //Step 2.
conn.Close();
foreach (DataRow dr in ds.Tables[0].Rows)
{
log.WriteLine(dr[0]); //Step 3.
}
log.Close();
}
Step 4.
private void contextMenuStripOpenInSqlStudio_Click(object sender, EventArgs e)
{
saveProcToAFile();
Process openSQL = new Process();
openSQL.StartInfo.FileName = "Ssms.exe";
openSQL.StartInfo.Arguments = "procedureToBeLoaded.sql";
openSQL.Start();
}

Related

c# update database isn't working

So I've searched the net to find a solution and what I found is that when we execute F5 in visual studio, it actually copies the original database into a new one and it uses the copy in the code so the changes you'd have made wouldn't be there and they told me to set the database properties to "Copy if newer" and it isn't working, I don't get any error messages but the original is not being updated.
I made a test to see if this code was updating at least the copy and it is...
After running my application when I see the database the changes aren't there
So I want to update the original database how do I do that?
private void button3_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["NembManagement.Properties.Settings.NembDatabaseConnectionString"].ConnectionString;
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand("UPDATE Alunos SET Nome = #a WHERE Id=1", connection))
{
DataTable AlunosInfo = new DataTable();
connection.Open();
command.Prepare();
command.Parameters.Clear();
command.Parameters.AddWithValue("#a","aff");
command.ExecuteNonQuery();
//test to see if it was updating the copy and it is
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Alunos WHERE Alunos.Id=1 ", connection);
adapter.Fill(AlunosInfo);
}
}
I found the solution somehow, i changed my database property Copy to nevercopy and i got another error saying that connection could not be opened so i solved this one by correcting the connection string in the app config

Run TSQLScripts via the Web Page in c# ASP.Net

I am trying to build the Web Page which can be used to run the TSQL scripts online.
My DB has so many databases and I am using the System Administrator account to execute these scripts.
After building the web page,
I can run the simple CRUD statements successfully in all databases
I can run the DML statements only for the default connected database, which is MyDB1.
Whenever, I create the new Object, it sits in the MyDB1. But I want to run / create objects in another DB.
I tried to run the following command, which is very simple and it works perfectly in SSMS.
USE MyDB2
GO
CREATE PROCEDURE [dbo].MyProc
AS
BEGIN
INSERT INTO
dbo.Table1
(
FieldA
, FieldB
, FieldC
)
VALUES
(
'AAA'
, 'BBB'
, 'CCC'
)
END
But I am getting the error message:
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
My c# code to execute the posted script is here:
DataTable dt = new DataTable();
try
{
using (SqlConnection cn = new SqlConnection("MyConnString"))
{
cn.Open();
SqlCommand cmd = new SqlCommand(sql, cn);
using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
if (dr.HasRows)
{
dt.Load(dr);
}
dr.Close();
}
cn.Close();
}
}
catch (Exception ex)
{
//Log Error
}
If I removed, USE statement, it was ok, but it created the object in the default DB which is MyDB1. How I can tweak my code to run it in MyDB2?
USE is an SSMS command, not a SQL statement.
Change your connect string to specify the appropriate database.

How to call multiple stored procedures in a MySql database

I am able to get this program to work with one stored procedure. Is it possible to call multiple stored procedures from MYSQL in C#? If so what is the most efficient way of doing so? Here is a snippet of my code to show what I've done thus far:
public static string RunSQL()
{
// Here is where it is connecting to local host.
string connStr = "server=localhost;user=xxxx;"
+ "database=xxxx;port=3306;password=xxx;"
+ "Allow User Variables=True";
MySqlConnection conn = new MySqlConnection(connStr);
// Here is where the connection gets opened.
conn.Open();
// Here I call the CN_renumber stored procedure.
MySqlCommand CN_renumber = new MySqlCommand("CN_renumber", conn);
CN_renumber.CommandType = System.Data.CommandType.StoredProcedure;
object result = CN_renumber.ExecuteNonQuery();
// Disconnect from local host.
conn.Close();
return result.ToString();
}
You can reuse your object of MySQLCommand multiple times, but before that you should make sure you call myCommand.Parameters.Clear();, then assign the new Stored Procedure name again.
Useful question with example here

Stored procedure - INSERT query does not work

I'm writing a music player application using WPF (C#). As part of its functionality, I'm populating a music library, where I'm storing the Title and Path to an mp3 file. The user gets to select a root folder for his music library and then the contents are populated in a "Songs" table. This is the code that I've written:
private void Populate_Click(object sender, RoutedEventArgs e)
{
// Folder browser
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.ShowDialog();
string DirectoryPath = System.IO.Path.GetDirectoryName(dlg.SelectedPath);
// Get the data directory
string[] A = Directory.GetFiles(DirectoryPath, "*.mp3", SearchOption.AllDirectories);
string[] fName = new string[A.Count()];
// Initialize connection
string connstr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
// Create the SqlCommand
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "InsertSongs";
// Create the parameters and execute the command
for (int i = 0; i < A.Count(); i++)
{
fName[i] = System.IO.Path.GetFileName(A[i]);
cmd.Parameters.AddWithValue("#Title", fName[i]);
cmd.Parameters.AddWithValue("#Path", A[i]);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Error: " + ex.Message);
}
finally
{
listBox1.Items.Add(A[i]);
listBox2.Items.Add(fName[i]);
cmd.Parameters.Clear();
}
}
// Close the connection
cmd.Dispose();
conn.Close();
conn.Dispose();
}
The code for the stored procedure is simple -
ALTER PROCEDURE dbo.InsertSongs
(
#Title nvarchar(50),
#Path nvarchar(50)
)
AS
INSERT INTO Songs(Title, Path) VALUES(#Title, #Path)
Now, when I execute the program, there is no error message thrown (the file names and directory names have size less than 50). However, at the end of execution, no value is inserted in the Songs table.
The Songs table is described as below:
ID int
Title nvarchar(50)
Path nvarchar(50)
I'm not sure where I went wrong: I have also tried using SqlParameter and then defining the type of parameter as NVARCHAR with size 50, but to no avail. May I kindly request you to assist me here? Many thanks in advance.
The whole User Instance and AttachDbFileName= approach is flawed - at best! Visual Studio will be copying around the .mdf file and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. SongsDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=SongsDatabase;Integrated Security=True
and everything else is exactly the same as before...

C# Winforms control - DataGridView - Update Database

The programs I am using are WAMP server (and its mysql feature in particular) and MS Visual Studio 2010 and I am programming in C#
Basically, here is what I need and can currently do with my application.
I have several datagridview's throughout the project and the first is simple, it loads all data from a specific table in the database at the push of a button. I have another form which I can insert records and have somehow managed to make a delete function which asks the user for 2 fields (first name and last name) and then it places these into a query and carries out the command.
What do I need to do?
I need to be able to implement some way for the form to update the database. I have chosen to do this through a datagridview control so the user can see what they are editting whilst they edit it.
I have the following code which I have tried to update the database based on the data in the datagridview control.
string connString = "server=localhost;User Id=root;database=collegelist;";
MySqlConnection conn = new MySqlConnection(connString);
string selectSQL = "SELECT * FROM collegeemployee";
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(selectSQL, conn);
MySqlCommandBuilder builder = new MySqlCommandBuilder(da);
DataTable table = new DataTable();
try
{
dgView2.Rows.RemoveAt(dgView2.CurrentRow.Index);
da.Update(table);
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
the problem with this code (listed in a method obviously) is that while the grid is able to be modified, it is unable to pass the data back to the database.
Instead of updating your database with the empty table what you should do is.
i.Get the datasource . like
ii. Update/synchronize the data source and data adapter
Here is the code it should work, if it doesn't please comment and tell me the problem.
string connString = "server=localhost;User Id=root;database=collegelist;";
MySqlConnection conn = new MySqlConnection(connString);
string selectSQL = "SELECT * FROM collegeemployee";
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(selectSQL, conn);
MySqlCommandBuilder builder = new MySqlCommandBuilder(da);
BindingSource BindingSourceToUpdate = (BindingSource)dgView2.DataSource; // because direct casting to data table was failing in VS2o1o
try
{
dgView2.Rows.RemoveAt(dgView2.CurrentRow.Index);
da.Update((DataTable)BindingSourceToUpdate.DataSource);
}
catch(exception)
{
}
conn.close();

Categories

Resources