Create SQL Server database from C# - using parameters - c#

I am trying to put up a code to create a databases from my C# code (asp.net website).
This is my code:
SqlCommand myCommand = new SqlCommand("CREATE DATABASE #dbname", nn);
myCommand.Parameters.Add("dbname", dbname);
myCommand.ExecuteNonQuery();
nn.Close();
well, its not working. its giving me an error:
incorrect syntax near '#dbname'
BUT. if I won't use parameters, people can SQL inj to my database. do you have any idea how can use anything, to get the database name from a textbox. and that people can't SQL inj me database?

You can't use parameters in CREATE DATABASE or other DDL commands.
I'd suggest using SQL Server Management Objects instead of SQL

Related

Change datasource in Visual Studio 2012 from SQLSRV to MySQL

I have a basic Application in Visual Studio 2012 which is connected to Sql Server 2008 R2 but now I want it to be connected only to a MySQL database (whose tables and columns are the same).
I downloaded MySQL for Visual Studio and I got a successfully connection in Data Sources to my database in MySQL.
Now I want to ask, what should I change from my app (apart of the connection string) if it only does simple CRUD with the db?
For example I've changed connection strings and when the app tried to search in db and fill a dataset I found an error in this code:
SqlDataAdapter dataAdapter = database.getPaquetes(date, _destino);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dgv_paqdisp.ReadOnly = true;
dgv_paqdisp.DataSource = ds.Tables[0];
ERROR:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server).
Are those types only for SQL Server? If yes, what is an equivalent when using MySQL?
Notice I don't want you to re-make my code or anything, I only want to know if there is something I'm missing or if its not that simple to change DataSource? Thanks in advance.
As WearWolf write you need a Mysql Connector/Net. You can download it from Nuget as packages. For the code that you have written for Sql Server will need to modified too much to get it worked on MySQL.
for example
SqlConnection will be MySqlConnection
SqlCommand will be MySqlCommand
You can do this changes Be Manual Find replace for every .cs file in solution carefully. At then end you will got working your app in MySQL.
You didn't mention that your CRUD is written using Entity framework and data-source tag make confusion here.
If you use Entity framework then simply generate the entity from database, because Mysql is a different database system you need to make the table in your mysql database first.
or if you use SQl queries execution for CRUD then just use given Find and replace and it will works.
You'll neet to add a reference to MySQL Connector/NET assemblies. They should come with MySQL for Visual Studio, otherwise that link has download instructions.
Then your code would become something like
MySqlDataAdapter dataAdapter = database.getPaquetes(date, _destino);
It shouldn't change much since both implemented using ADO.net

Get name of "parent" database from assembly

I have a SQL CLR stored procedure written in c# (.NET4). Its purpose is to allow a trigger on a table in a SQL Server 2012 database to call a web service which then processes the data in that table.
However, there are several different databases which will all have triggers using this assembly. My web service needs to know which database is triggered the call to it in order to know where to get the data from.
I could simply add a parameter to my stored procedure but I want to keep things simple from the database side. Is there any way, in .NET, to obtain information about the database to which the assembly is attached?
Aah, found one:
This still opens a context connection to the database, but it's about the only way I can see.
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
conn.Open();
string dbName = conn.Database
}
That's from an MSDN article. Also, the MSDN article on Context Connection.

Calling a Sybase SP, error "SP not found"

I am connecting to a Sybase 9 database to retrieve data. I can query the database without issue using ODBC connections but I am having an issue calling stored procedures. The procedure was written probably 6-7 years ago. This is what I have to execute the stored procedure.
OdbcCommand itemWeightAve = conn.CreateCommand();
itemWeightAve.CommandText = "ComputeLastCost";
itemWeightAve.CommandType = CommandType.StoredProcedure;
itemWeightAve.Parameters.AddWithValue("#OwnerId", "BananaHammock");//company number
itemWeightAve.Parameters.AddWithValue("#InventoryId", InventoryNumberHere);//inventory id from query results
itemWeightAve.Parameters.AddWithValue("#EndDate", EndDateHere);//end date from query results
OdbcDataReader itemAveReader = itemWeightAve.ExecuteReader();
I am not very familiar with Sybase or ODBC and the version these guys are using is extremely old and is no longer officially supported. Upgrading the Sybase database is out of the question. The error I get when attempting to execute this command is...
ERROR [42S02] [Sybase][ODBC Driver][Adaptive Server Anywhere]
Procedure 'ComputeLastCost' not found
I know that the procedure exists, it is typed correctly, and that the parameter names exist and are typed correctly. Does anyone have any tips/hints/suggestions for what I'm doing wrong here?
Turned the comment into an answer...
What is the default database of the login that you are using?
Is the stored procedure in the same database?
If not, you need to prefix your procedure name with the database name "sharedDB.ComputeLastCost".
You can check this by logging in with the same user/password through isql and try and exec it by hand. if you have to do a use database (ie. use database sharedDB) before you execute it, you need to put the db name in front.
You can also change your default database for the user. Either way should work.

Save SQL DataSet to Local MDB File

Context
My appliction uses an SQL database from which it reads my datatables at start of my application. If the application would fail to connect to the SQL DB, I have a local Ms Access .MDB file. I have a separate thread that checks if the local database is outdated.
I have a DataTable which I obtain from my SQL connection --> Verified and working
I can connect to my Access database locally and read from it --> Verified and working
Issue/Question
I'm trying to update my local database by updating it with the DataTable I obtained from my SQL Connection.
public static void UpdateLocalDatabase(string strTableName, OleDbConnection MyConnection, DataTable MyTable)
{
try
{
if (CreateDatabaseConnection() != null)
{
string strQuery = "SELECT * FROM " + strTableName;
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
OleDbCommandBuilder MyCommandBuilder = new OleDbCommandBuilder(MyAdapter);
MyAdapter.SelectCommand = new OleDbCommand(strQuery, odcConnection);
MyAdapter.UpdateCommand = MyCommandBuilder.GetUpdateCommand();
MyConn.Open();
MyAdapter.Update(MyTable);
MyConn.Close();
}
}
catch { }
}
If I debug this snippet, all variables are what they should be:
strTableName = the correct name for my table
MyConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyLocation;Persist Security Info=True;JET OLEDB:Database Password=MyPassword;"
MyTable = is the correct table that is also used further on by my application
This process runs through without an error and without using the catch but it does not touch my database, it just doesn't do a thing.
Am I dropping the ball here or just missing the obvious, I have no idea but I browsed many articles and apart for showing the MyAdapter.Update(), there doesn't seem to be much more to it.
Any help is welcome.
Thanks,
Kevin
Does your backup database have to be in access? because if you used SQL Compact Edition it'd be much easier to copy between the two?
Yes, it would either mean attaching it with your installer or just ensuring that all client machines have it pre-installed, it is free however.
if this is an issue then all you need to do (I think, not done it myself)
would be to go to your installer projects properties, click prerequisites and then tick SQL compact so that it will be installed before your application can be used, iv done this before with other frameworks and it just pops up a box with the install shield asking whether they want to download the necessary software and its just one click then it should be done for them.
Do you need a hand on using the compact database also?
One negative by the way is it does lack some higher end features but shouldn't affect average database work
EDIT
if you will be using sql CE you can easily make the databse in VS by clicking data and new data source then following the steps making sure to put sql CE when asked
if it works, you'll end up with an .sdf database
I provided a code snippet that fixed the issue on my related question here: Export SQL DataBase to WinForm DataSet and then to MDB Database using DataSet

INSERT from ASP.NET to MS Access

We are trying to build a Help Desk ticketing system just for intranet. Deciding upon the ASP .NET (C#) with Visual Studio 2008 Express (think we have a full version floating around if we need it). Nothing fancy, couple of pages grabbing NTLM information, system information and storing it along with their problem in a database. Goal is to make it simple, but instead of using our SQL Server 2000 back end, the admin wants me to use MS Access. I have the GridView and connections running smooth. Can pull select queries until my heart is content. However, tying in a couple variables with a text box on a submit button into say an INSERT statement.. well I don't even know where to begin with MS Access. Every internet example is in VB .NET plus seems to be hand coding what Visual Studio has already done for me in a few clicks.
Is MS Access going to be too hard for all we want to do? If not, where do we begin to simply submit this data into the tables?
Edit: After a bunch of playing around we have the OleDB working. It's not pretty, yes SQL Server would be awesome but, sometimes you just have to play ball.
Edit: Anyone looking for an actual coded answer, here you are. There has got to be others out there in the same boat.
string userIP = Request.UserHostAddress.ToString();
string userDNS = Request.UserHostName.ToString();
string duser = Request.ServerVariables["LOGON_USER"]; //NTLM Domain\Username
string computer = System.Environment.MachineName.ToString(); //Computer Name
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\helpdesk.MDB;";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO ticketing ([user], [comp], [issue]) VALUES (#duser, #computer, #col3)";
cmd.Parameters.Add("#duser", OleDbType.VarChar).Value = duser;
cmd.Parameters.Add("#computer", OleDbType.VarChar).Value = computer;
cmd.Parameters.Add("#col3", OleDbType.LongVarChar).Value = TextBox1.Text;
cmd.ExecuteNonQuery();
conn.Close();
The admin is nuts. Access is an in-process database, and as such is not well suited for web sites where users will be creating or updating records.
But as far as creating INSERT queries go, Access is no harder than anything else. If you can't create INSERT queries for Access you'll probably have trouble with SQL Server as well.
I also suggest using SQL Server, but considering your problem:
What is your problem writing an INSERT query for Access ?
You should make use of the classes that you'll find in the System.Data.OleDb namespace:
OleDbConnection
OleDbCommand
Quick'n dirty code (not compiled whatsoever):
OleDbConnection conn = new OleDbConnection (connectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText= "INSERT INTO myTable (col1, col2) VALUES (#p_col1, #p_col2)";
command.Parameters.Add ("#p_col1", OleDbType.String).Value = textBox1.Text;
...
command.ExecuteNonQUery();
There are some caveats with the OleDb classes however (like adding the Parameters to the collection in the order that they occur in your SQL statement, for instance).
Don't bother with Access. Use SQL Server Express. There's also an admin tool for it that looks like the full blown SQL Server management tool.
Access has its place, and can usually do more than what most people give it credit for, but yes you want to use SQL Server in ones of its many forms (eg. SQL Server Express) or another proper "server" database for a web app like this.

Categories