incorrect syntax in c# sql command - c#

I've got the following
SqlCommand cmd = getSQLCommand();
using (cmd.Connection)
using (cmd)
{
try
{
string dbName = txt_DatabaseName.Text;
var createDatabaseQuery = "exec ('CREATE DATABASE ' + #databaseName)";
var sqlCommand = new SqlCommand(createDatabaseQuery, cmd.Connection);
sqlCommand.Parameters.Add("#databaseName", SqlDbType.Text);
sqlCommand.Parameters["#databaseName"].Value = dbName.ToString();
cmd.Connection.Open();
sqlCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('SQL Error. Record not added.')", true);
}
finally
{
cmd.Connection.Close();
}
}
I'm fully aware that params are not supported in DDL operations, so I've got this really cool thread that I've been using to help me write the contents within the "try".
How to use SqlCommand to CREATE DATABASE with parameterized db name?
That said, I'm still getting an exception error for incorrect syntax near 'Database'. This might be a user error but I've been stuck around this for an hour or so now.
Any thoughts/ improvements?
p.s. All I'm trying to do is to create a database programmatically by using a dynamic value of whatever happens to be in txt_DatabaseName.Text (and yes I will try to error handle this in case there's white spaces entered or any chars that are not supported in SQL.
p.p.s Any articles that I can have a look at against sql injection attacks or any suggestions around constructing the method I have to prevent it? This is a simple exercise that I'm doing on my local machine, not public facing but still would like to get ahead of the game if possible.

You don't need the exec part at all. Again you are getting error after removing exec cause you are wrapping your query in single quote 'CREATE DATABASE ' which is getting considered as string literal. It should just be
var createDatabaseQuery = string.Format("CREATE DATABASE {0}",DBnamevariable);
var sqlCommand = new SqlCommand(createDatabaseQuery, cmd.Connection);

Take a look with the sql profiler to see what is being fired against the database. If it is not working try to execute the query in Management studio to see it that is working. It's probably some kind of special character that is not allowed.

Related

Why is my SMO Query returning -1 for each GO statement?

I am using Microsoft's SMO (SQL Server Management Objects) to execute a SQL script that contains GO Statements, since the regular System.Data.SqlClient does not recognize GO as a command. It is actually running fine (I think..) but it seems to be returning a -1 for every GO Statement. So with the following code..
using (var cnn = new SqlConnection(connectionString))
{
try
{
cnn.Open();
Console.WriteLine("Connection Successful!");
var server = new Server(new ServerConnection(cnn));
var rows = server.ConnectionContext.ExecuteNonQuery(SqlStuff.CommandText);
Console.WriteLine($"Script Successful: {rows} affected");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Cannot connect to Server: " + ex.Message);
Console.ReadLine();
}
}
my console reads "Script Successful: -47 affected", which after looking at my script is the exact number of GOs I have. Is that normal for my query to return a -1 for each GO? I can't seem to find documentation on it, and it concerns me that part of my query is not executing correctly even though at this time it seems to have generated the tables I need. It is my first time using SMO and I just need to make sure this is normal.

get next sequence value Oracle using Ado.Net c#

I have tried various forms of the following method to get the next sequence value from an Oracle DB in my asp.net app. The sql statement works fine in Toad (11g). The sql statement includes "Select ... myschema.mySeq.nextval ... from dual. But the error I receive when I get to cmd.ExecuteNonQuery() -- the error is:
>
Exception Details: Oracle.DataAccess.Client.OracleException: ORA-00942: table or view does not exist
<<
Authentication is a very big deal at the place where I am at. Is this a data Access problem or is something incorrect with my method (below)? If something is incorrect with the code below what is the correction I need to make? Note: the app (big app) has hundreds of calls to SPs (which all work fine), so I basically copied the connection string code and used a constant (like they do throughout the app). If I use an SP this works, but I want to not use an SP just straight forward Ado.Net. What is the fix?
public int getNextPositionSequence(string userSeq)
{
OracleConnection conn = new OracleConnection(DaoHelper.GetConnectionString("AuthenticatedOracleConnectionString"));
conn.Open();
conn.ClientId = userSeq;
string sql = "SELECT ddtms.position_seq.nextval from dual";
OracleCommand cmd = new OracleCommand(sql, conn);
object s = cmd.ExecuteNonQuery(); //<<<--- crashes here
conn.Close();
return 1;
}

Error "ORA-00933: SQL command not properly ended" on Select with ODBC Command

I'm trying to execute a query against an Oracle DB using ODBC in .NET and am getting the following error:
ORA-00933: SQL command not properly ended
However, the SQL statement is definitely correct, and I can execute it successfully from Oracle SQL Developer. The query itself looks like this:
SELECT * FROM TABLE(SCHEMA.PKG.SPNAME('PARAMS'));
Another simple query works fine:
SELECT COUNT(*) FROM SCHEMA.MYTABLE
It looks like something with the former, where it's using a package in the query and causing something to break. The error indicates that it's not properly ended, but it has a semi-colon and correct braces, so it seems something else is going on.
If I remove the trailing semi-colon, I get an error with no message.
My C# code is basic and looks like this:
using (var connection = new OdbcConnection(connectionString))
{
using (var command = connection.CreateCommand())
{
command.CommandText = commandText;
connection.Open();
var result = command.ExecuteScalar();
connection.Close();
Console.WriteLine(result);
}
}
When using the Oracle library for .NET, it works when I remove the trailing semi-colon. If I keep that in place, the same error about the SQL command not being properly ended comes up.
It seems like this query should work with ODBC. Is there anything I need to differently to get it working, or is using the Oracle Managed Data Provider the only way?
From my experience, I have noticed several instances where a semicolon will break the query, such as JasperSoft Studio and the cx_Oracle Python module. I know very little about ODBC vs OracleDataClient, but I would imagine this is a similar situation.
I would not use ODBC I would actually do something like this using the OracleDataClient
var strSQL = "SELECT * FROM TABLE(SCHEMA.PKG.SPNAME('PARAMS'));";
using (OracleConnection connStr = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand(strSQL, connStr))
{
cmd.CommandType = CommandType.Text;
cmd.Connection.Open();
cmd.ExecuteScalar(); //change the ExecuteScalar to fit the proper call
}
}

Update table (rows) Access 2007 and C# 2010

So this is probably the most naive question but that is what questions are for I guess;
Then, my issue is that I have no idea on how to connect Visual C# Express 2010 to Access 2007 and do the typical insert, update, delete, search in an application in C#, I have just learned the basics (finished a console tutorial, which I believe is more than enought, having previous background of VB6 using access 97), and I have been searching here and in the web, but the only thing I could find where the msdn tutorials which I dind't find really clear.
So in my app I just need to link comboboxes, query those values to obtain new ones, do calculations and then store in arrays (and maybe show these in datagrids as well as edit them from said datagrids, which is a bit more complicated I guess) and finally store them in various tables, but I haven't really found a strong (or most likely simple) manual that will guide me to create the typical app insert, update, delete using winforms.
Do you guys have any good links in order to do this?
Thanks.
You can try with this code
Here link about string connection : http://www.connectionstrings.com/access-2007
var query = "...";
var connectionString = "...";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
using(var command = new OleDbCommand(query))
{
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the insert command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
}

How to attach a database using a program deployed by C#?

i wanna to attach a Database from a dynamic path to a MSSQL server by coding a project to do this ,,
what is the code i should write and will it be a Windows Application or Console Application ,, or there is no difference ??
You can use any of the two. Just make sure the files are in a place the SQL Server in question can reach and then attach them with an sql statement.
Like this:
CREATE DATABASE [AdventureWorks] ON
( FILENAME = N’C:\Data\AdventureWorks_Data.mdf’ ),
( FILENAME = N’C:\Data\AdventureWorks_Log.ldf’ )
FOR ATTACH
In the connection string you can attach a database if the database has not already been attached. To do this in C# you should be able to do the following (this is untested):
SQLConnection conn;
try
{
conn = new SQLConnection(String.Format("Server={0};AttachDbFilename={1};Database=dbname; Trusted_Connection=Yes;", "Server Address", #"Path To Database"));
conn.Open();
conn.Close();
}
catch (Exception ex)
{
throw;
}
finally
{
conn.Dispose();
}
Let me know how you get on.
Regards,
Stu
Are you talking about using System.Data.SqlConnection class?
You can dynamically build your connectionString when you create your SqlConnection.
If I nderstand your question correctly, you are looking for a way to use a databse which the user will select (not the hard coded one).
Go here and learn about Saving User and Application Settings in WinForms. You will get some ideas.

Categories

Resources