Does anyone know why the first code works but the second does not?
At the second I get exception (wrong syntax near #databaseName).
First Code
public void CreateDatabase(string databaseName)
{
string command = "CREATE DATABASE " + databaseName;
using (SqlConnection sqlConn = new SqlConnection(_sqlConnectionStringBuilder.ToString()))
{
sqlConn.Open();
using (SqlCommand sqlComm = new SqlCommand(command, sqlConn))
{
sqlComm.ExecuteNonQuery()
}
}
}
Second Code
public void CreateDatabase(string databaseName)
{
string command = "CREATE DATABASE #databaseName"; \\I tried both
string command = "CREATE DATABASE '#databaseName'"; \\I tried both
using (SqlConnection sqlConn = new SqlConnection(_sqlConnectionStringBuilder.ToString()))
{
sqlConn.Open();
using (SqlCommand sqlComm = new SqlCommand(command, sqlConn))
{
sqlComm.Parameters.Add(new SqlParameter(#"databaseName", databaseName));
sqlComm.ExecuteNonQuery()
}
}
}
In TSQL the general rule is you can't parameterize Data Definition Language (DDL) statements at all. And you can't use parameters in place of identifiers in Data Manipulation Language (DML) statements.
Related
Can you please provide an answer following sql query to linq . I have some knowledge about linq but i am confused about sql reader object ..
public AccountBalanceRequest AccountBalanceCheek(AccountBalanceRequest accountNumber)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
var cmd = new SqlCommand("SELECT Account_Type,Account_Fees,Account_Balance,Over_Draft_Limit FROM Current_Account_Details WHERE Account_Number = '" + accountNumber.Account_Number + "'", conn);
cmd.CommandType = CommandType.Text;
var reader = cmd.ExecuteReader();
//read the result of the execute command.
while (reader.Read())
{
//assuming that your property is the same as your table schema. refer to your table schema Current_Account_Details
accountNumber.Account_Type = reader["Account_Type"].ToString();
accountNumber.Account_Fee = reader["Account_Fees"].ToString();
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Over_Draft_Limit = reader["Over_Draft_Limit"].ToString();
}
return accountNumber;
}
}
First you have to have DbContext which you must instantiate in using(usual practice):
using (DbContext db = new DbContext())
{
var results = (from ad in db.Current_Account_Details
where ad.Account_Number == accountNumber.Account_Number
select ad).ToList();
}
Make sure you have created the object data model from database.
I do not get the other part of your post but this would be the general idea of how to write Linq2Entities queries.
My code:
string SqlSelectQuery = " Select * From [KTS MANAGMENT] Where STAFF NAME=" + Convert.ToString(textBox1.Text);
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
SqlDataReader dr = cmd.ExecuteReader();
I get this error:
An expression of non-boolean type specified in a context where a condition is expected, near 'NAME'
You should always use parametrized queries to avoid SQL injection - still the #1 vulnerability in computing.
Thus, your code should be something like this:
string connectionString = "......"; // typically read from config file
string query = "SELECT * FROM [KTS MANAGMENT] WHERE STAFF NAME = #Name";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, con)
{
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = textBox1.Text;
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
// read the values from the SQL data reader....
}
con.Close();
}
This approach also avoid the error you have with missing and/or mismatched single or double quotes around strings in a SQL statement ...
I wants to fetch the data from database using C++.Net. I need to do this irrespective of db used in the system. But i don't want to change my code for each database. I am looking for a solution in C++.Net, please do help..
This is what i have now;
Oracle:
OracleConnection *myOracleConnection;
OracleDataAdapter * myDataAdapter;
DataSet * myDataSet;
myOracleConnection = new OracleConnection(S"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.2.175)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SCDB)));User Id=user;Password=pw;");
myOracleConnection->Open();
myDataAdapter = new OracleDataAdapter(S"select dbms_xmlgen.getxml(' select * from SampleTable') from dual ",myOracleConnection);
myDataSet = new DataSet("Sample");
Sql:
`SqlConnection *mySQLConnection;
SqlDataAdapter * myDataAdapter;
DataSet * myDataSet;
mySQLConnection = new SqlConnection(S"Data Source=(local);Initial Catalog=myDb;User Id=user;Password=pw;");
mySQLConnection->Open();
myDataAdapter = new SqlDataAdapter(S"select * from [SampleTable]",mySQLConnection);
myDataSet = new DataSet("Sample");`
i wants to do both connection using one connection object. Is there any idea to achieve this???
I can't give you c++ code, but I can help you how to do it. It will be difficult to do it in one connection, but your can get a DataSet back which will work, and you only have to do the code once.
Create a method will return a DataSet, and pass the query as well as what type of connection should be used, in this method depending on tour connection type you do your query and return your result.
You can also add a connectionstring if you wish.
Something like this (it is c# though)
DataSet GetDataSet(string sqlQuery, ConnectionType connType)
{
DataSet dataset = new DataSet("aDataSet");
using (DataTable table = dataset.Tables.Add("aDataTable"))
{
switch (connType)
{
case ConnectionType.MSSQL:
using (var conn = new SqlConnection("Data Source=(local);Initial Catalog=myDb;User Id=user;Password=pw"))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
{
table.Load(reader);
}
}
}
break;
case ConnectionType.Oracle:
using (var conn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.2.175)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SCDB)));User Id=user;Password=pw"))
{
using (var cmd = new OracleCommand(sqlQuery, conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
{
table.Load(reader);
}
}
}
break;
default:
break;
}
}
return dataset;
}
enum ConnectionType { MSSQL, Oracle }
I am trying to write a Windows Form program on top of .NET 4.0 and accessing Microsoft Access Database. I can read and write with no problem but sometimes, I get this error:
COM object that has been separated from its underlying RCW cannot be used.
I tried to call this method (GetIDBasedonTeamName) with different inputs twice (on the same thread). The second time this is run, I got that error.
OleDbConnection conn = new OleDbConnection();
OleDbConnection mDB = new OleDbConnection();
OleDbCommand comm = new OleDbCommand();
OleDbCommand cmd;
OleDbDataReader dr;
public void OpenConnection(string name) // always call this method first in other methods to initialise connection
{
conn.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0;Data source="
+ Application.StartupPath + "\\AppData\\" + name + ".mdb;";
conn.Open();
comm.Connection = conn;
comm.Parameters.Clear();
}
public string GetIDBasedonTeamName(string teamName)
{
string toReturn = "";
try
{
OpenConnection("form");
comm.CommandText = "Select ID from TeamDetails WHERE TeamName=#teamName";
comm.Parameters.AddWithValue("TeamName", teamName);
dr = comm.ExecuteReader();
while (dr.Read())
{
toReturn = dr[0].ToString();
}
}
catch (OleDbException e)
{
string err = e.Message.ToString();
return null;
}
finally
{
}
conn.Close();
dr.Close();
return toReturn;
}
Exception happened on dr = comm.ExecuteReader();.
The method that was calling this method have this 2 lines inside:
InfoConfig.team1id = Convert.ToInt32(dbm.GetIDBasedonTeamName(cbxTeam1.Text));
InfoConfig.team2id = Convert.ToInt32(dbm.GetIDBasedonTeamName(cbxTeam2.Text));
What could be the cause? I read around and they mentioned not to use different threads but it is the same thread here.
Thanks,
Guo Hong
Building on Martin Liversage's answer:
public string GetIDBasedonTeamName(string teamName) {
var connString = "Provider = Microsoft.Jet.OLEDB.4.0;Data source="
+ Application.StartupPath + "\\AppData\\" + name + ".mdb;";
using (var conn = new OleDbConnection(connString)) {
conn.Open();
using (var cmd = conn.CreateCommand()) {
cmd.CommandText="Select ID from TeamDetails WHERE TeamName = #teamName";
cmd.Parameters.AddWithValue("TeamName", teamName);
using (var rdr = cmd.ExecuteReader()) {
if (rdr.Read()) {
return (string)rdr["TeamName"];
}
//if no valid results will return null
}
}
}
}
Instead of creating the objects only once and storing them in fields in your class you should create, use and close the objects in your method. It is probably the Close you call in the end the method that releases the underlying COM objects giving you the exception on the second call.
I am trying to retrieve some rows from the database using simple SELECT statement in SQL and displaying them in a Data Grid, Now what I have to do is to multiply the retrieved values with some factor and then display it. I am trying to achieve it the following way:
I have declared PerDoseSize1 as a double variable which gets its value from a function. I am not able to do it this way.
It gives me an error saying "PerDoseSize1 is not a valid column"
public void FillDG1(string Chemical_Name0, string Chemical_Name1, string Chemical_Name2, string Chemical_Name3,double PerDoseSize1)
{
objDs.Clear();
string connString ="Data Source=dk1;Integrated Security=True";
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT [Chemical Name],([GWP])*(perdosesize) AS GlobalWarming, ([ODP])*(perdosesize) AS OzoneDepletion, [WDP] AS WaterDepletion ,[FDP] AS FossilDepletion FROM [Surfactants$] WHERE ([Chemical Name] IN ( #ChemicalName0, #ChemicalName1,#ChemicalName2 ,#ChemicalName3)) ";
cmd.Parameters.AddWithValue("#ChemicalName0",Chemical_Name0);
cmd.Parameters.AddWithValue("#ChemicalName1", Chemical_Name1);
cmd.Parameters.AddWithValue("#ChemicalName2", Chemical_Name2);
cmd.Parameters.AddWithValue("#ChemicalName3", Chemical_Name3);
cmd.Parameters.AddWithValue("#perdosesize", PerDoseSize1);
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
dAdapter.Fill(objDs);
DataTable myDataTable = objDs.Tables[0];
DG1.DataContext = objDs.Tables[0].DefaultView;
cmd.ExecuteNonQuery();
MessageBox.Show(ChemicalName0,ChemicalName1);
con.Close();
}
It still doesn't seem to work, Is it still wrong? Please help!
The way you have written it:
"SELECT ([GWP])*(PerDoseSize1) AS GlobalWarming, ([ODP])*(PerDoseSize1)
Will not work because the function argument you're passing in won't be substituted in your SQL.
So you can try creating a Parameter argument for PerDoseSize1 and pass it into the SQL, like you're doing with AddWithValue.
I have declared PerDoseSize1 as a
double variable which gets its value
from a function
So what? How does that get into the SQL? So far there is NOTHING saying this. YOU have to put it into the SQL and assign it to a parameter. It wont magically hook up.