I'm making a table, if the name doesn't already exist
string sc1 = #"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_NAME = #name) SELECT 1 ELSE SELECT 0";
string sc2 = #"CREATE TABLE dbo.Data" + pv.tablecounter + "(testdescription VARCHAR(25), testvalue VARCHAR(5))";
SqlCommand check1 = new SqlCommand(sc1, connection);
check1.Parameters.Add("#name", SqlDbType.VarChar).Value = "Data" + pv.tablecounter;
SqlCommand check2 = new SqlCommand(sc2, connection);
exists = Convert.ToInt32(chec.ExecuteScalar());
if(exists == 1)
{
MessageBox.Show("table exists, will not create new one");
}
else
{
MessageBox.Show("table wasn't found, creating now");
check2.ExecuteNonQuery();
}
i can verify that this is all "working" (the correct message will show, and it will find the newly created table and give me the right message). My connection string works fine
my question is, where did it go? i can't browse and find it in the server explorer. this is probably basic but i cannot find any info about it. I have tried specifying the database
#"CREATE TABLE testdb.dbo.Data" + pv.tablecounter + "(testdescription VARCHAR(25), testvalue VARCHAR(5))";
Wth an error that database testdb does not exist , even though it's in my server explorer and i have been writing to it elsewhere using the same connection string
using Visual Studio 2017
thanks
Related
i create a database with access and used this database in an Windows forms app.
I can select and insert rows from the database but i can't delete and update the database.
I used the following code. The first part works, the second doesen't.
if (!string.IsNullOrEmpty(this.txb_Box.Text) && !string.IsNullOrEmpty(this.txb_Teil.Text))
{
this.select = "SELECT * FROM Lagerhaltung WHERE BoxNr='"+ this.txb_Box.Text+"' AND Reklamation='"+this.txb_Teil+"'";
DbCommand command2 = connection2.CreateCommand();
command2.CommandText = this.select;
DbDataReader reader2 = command2.ExecuteReader();
if(!reader2.HasRows)
{
this.select = "INSERT INTO Lagerhaltung ( BoxNr, Reklamation, EingelagertAm, Artikelnr) VALUES ('" + this.txb_Box + "','"+this.txb_Teil.Text+"','" + this.lbl_Datum.Text + "', 'Test')";
}
}
"UPDATE Lagerhaltung SET AusgelagertAm='"+this.lbl_Datum.Text+"', Erledigt= True WHERE id like '"+data.id+"'";
"DELETE FROM Lagerhaltung WHERE id like '1'";
Can someone help me?
Best regards
JuRi-2020
I find the mistake. I don't activate the command with
command.ExecuteNonQuery();
that's why nothing happened.
I would like to create a method to know if a value exists in a sql server database field or not using C#, the name of the server is "myServer", the name of database is "myDatabase", the name of table is "myTable ", the name of the field is "myField" and the value is "myValue". I check the following method but it doesn't work :
public bool myValueExist(string myTable, string myField, string myValue)
{
int result = 0;
SqlCommand cmd = new SqlCommand("select COUNT(*) from '" + myTable + "' where'"+myField+"=#myValue", cnx);
cmd.Parameters.AddWithValue("#myValue", myValue);
result = (int) cmd.ExecuteScalar();
if (result == 0) return false;
else return true;
}
the connection is established to sql server.
Can some one help me, thank you in advance.
You've got a mess of the query string itself. Without a specific error message I can't tell more, but what is obvious is the following.
Assuming myTable = Foo and myField = Bar your variable of cmd would generate to
select COUNT(*) from'Foo' where'Bar=#myValue
As you can see that is just wrong. It should be
select Count(*) from Foo where Bar = #myValue
One possible solution might be:
SqlCommand cmd = new SqlCommand("select COUNT(*) from " + myTable + " where "+ myField + "=#myValue", cnx);
Also, using 'using' on SQLConnection, command etc is a good idea for disposing the resources.
I am trying to carry out an 'insert if not exists' statement, i am not receiving any errors and the row does not exist in the db, however it still will not add it. Executing a normal 'insert' works but not when the 'if not exists' is added.
I have also tried including BEGIN & END and it doesnt work.
Where am i going wrong??
string getStudentModuleId = "SELECT ModuleId FROM StudentModuleMarks WHERE Mark < 40";
SqlCommand myCommand = new SqlCommand(getStudentModuleId, MyConnection3);
try
{
moduleid = (int)myCommand.ExecuteScalar();
string addRepeat = "IF NOT EXISTS (SELECT * FROM StudentModules WHERE ModuleId = #moduleid AND SchoolYear = '2018') INSERT INTO StudentModules(StudentDegreeId, ModuleId, Repeat, SchoolYear, EnrolledStatus) VALUES (1,#moduleid,1,'2018','Active')";
SqlCommand command = new SqlCommand(addRepeat, MyConnection3);
command.Parameters.AddWithValue("#moduleid", moduleid);
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
It seems you are using sql server, For MySQL, you can follow this technique to insert record if it doesn't exist :
INSERT INTO StudentModules(StudentDegreeId, ModuleId, Repeat, SchoolYear, EnrolledStatus)
select 1,#moduleid, 1, '2018', 'Active' from dual
where NOT EXISTS (SELECT * FROM StudentModules WHERE ModuleId = #moduleid AND SchoolYear = '2018')
Please note that, in MySQL, you don't really need to have a table called dual to exist: it is a special table-name that can be used to select anything from it. And it will output a single record always with a SELECT query like above.
I'm very new to C#, and I just learn coding as one of my hobbies.
I'm trying to develop a stand-alone Windows application using Visual Studio and an Access database.
I have some difficulties how to access the database.
Project is my table in the Access database and projectname and path are my columns in the project table.
I'm trying to read the folders Name in a certain path and writing the name and path of a folder into my table.
How do I compare and insert only the new folder created?
This is showing an error in my insert syntax!
string[] files = Directory.GetDirectories(#"C:\\SomePath\\Project_1\\Project_1\\Resources");
foreach (string file in files)
{
string name = new DirectoryInfo(file).Name;
String Root = Path.GetFullPath(file);
connection_2.Open();
OleDbCommand ListWrite = new OleDbCommand();
ListWrite.Connection = connection_2;
ListWrite.CommandText= "insert into Project (projectname,path) values ('" + name + "','" +Root+ "') where'"
+ name + "' != projectname ";
ListWrite.ExecuteNonQuery();
connection_2.Close();
}
An insert command does not allow a where statement the way you use it.
You will need to query the table for each of the directory names. If the result of the query is not empty, the specific directory name it is already present in the table. Otherwise, you can insert the new name with an insert.
I would suggest to write a new method for that check:
public bool DoesFolderAlreadyExistInTable(string folder_name, string path, OleDbConnection connection)
{
using (var ListWrite = new OleDbCommand("select count(*) as c from Project where name=#name and path=#path", connection)) {
ListWrite.Parameters.AddWithValue("#name", folder_name);
ListWrite.Parameters.AddWithValue("#path", path);
var result = ListWrite.ExecuteReader();
return result.Read() && result.GetInt32(0) > 0;
}
}
You just need to leave a space after where:
..where '...
However, the best solution for not having such issues as well as SQL injection is to use parameters:
ListWrite.CommandText= "insert into Project (projectname,path) values (#name, #path)";
ListWrite.Parameters.Add("#name",SqlDbType.NVarChar).Value = name;
ListWrite.Parameters.Add("#path",SqlDbType.NVarChar).Value = Root;
Also notice that the where clause does not have any sense in an insert statement. You have to handle it from code or putting a unique constraint on the projectname column.
A WHERE clause is not valid in an insert statement. I assume what you were attempting to do was prevent duplicate project names. One way you can do this in SQL Server is as shown, I've made the assumption it's valid in Access as well but this isn't always the case.
SQL
INSERT INTO Project (projectname, path)
SELECT DISTINCT 'yourpath', 'yourroot'
FROM Project
WHERE NOT EXISTS (SELECT projectname FROM Project WHERE projectname = 'yourpath')
C#
ListWrite.CommandText= "insert into Project (projectname,path) select distinct '" + name + "','" + Root + "') from Project where not exists (select projectname from Project where projectname = '" + name + "'";
As pointed out by LosWochos and apomene, you should also look into parameterized SQL.
I'm using Oracle's ODAC.NET for a .NET 3.5 project against an Oracle 11 Express database, and I'm seeing behavior that I can't explain (and can't seem to work around).
ODAC should be the latest, I just pulled it 3 days ago, but the versions are as follows:
Oracle.DataAccess.dll version 2.112.3.0 (release 5)
oci.dll (instant client) version 11.2.0.1
I have a Table, People, that has 3 columns:
ID
FirstName
LastName
In code I run an ALTER TABLE command, using OracleCommand.ExecuteNonQuery, to add a new column named "MIDDLE_NAME" to the table. That command succeeds. If I look at the table with Oracle SQL Developer, the columns shows up. All well and good.
Now if I run use OracleCommand.ExecuteReader with a command text of SELECT * FROM People right after I do the alter table, I get back data with only 3 columns, not 4!
Here is code that reproduces the problem:
public void FieldTest()
{
var sql1 = "CREATE TABLE People (" +
"ID NUMBER PRIMARY KEY, " +
"FirstName NVARCHAR2 (200), " +
"LastName NVARCHAR2 (200) NOT NULL)";
var sql2 = "ALTER TABLE People " +
"ADD Middle_Name NUMBER";
var sql3 = "SELECT * FROM People";
var sql4 = "SELECT column_name FROM all_tab_cols WHERE table_name = 'PEOPLE'";
var cnInfo = new OracleConnectionInfo("192.168.10.246", 1521, "XE", "system", "password");
var connectionString = BuildConnectionString(cnInfo);
using (var connection = new OracleConnection(connectionString))
{
connection.Open();
using (var create = new OracleCommand(sql1, connection))
{
create.ExecuteNonQuery();
}
using (var get = new OracleCommand(sql3, connection))
{
using (var reader = get.ExecuteReader())
{
Debug.WriteLine("Columns: " + reader.FieldCount);
// outputs 3, which is right
}
}
using (var alter = new OracleCommand(sql2, connection))
{
alter.ExecuteNonQuery();
}
using (var get = new OracleCommand(sql3, connection))
{
using (var reader = get.ExecuteReader())
{
Debug.WriteLine("Columns: " + reader.FieldCount);
// outputs 3, which is *wrong* <---- Here's the problem
}
}
using (var cols = new OracleCommand(sql4, connection))
{
using (var reader = cols.ExecuteReader())
{
int count = 0;
while (reader.Read())
{
count++;
Debug.WriteLine("Col: " + reader.GetString(0));
}
Debug.WriteLine("Columns: " + count.ToString());
// outputs 4, which is right
}
}
}
}
I've tried some things to prevent the behavior, and none of them give me back the 4th column:
I close the connection and re-open it
I use a new OracleConnection for the SELECT than for the ALTER
I use the same OracleConnection for the SELECT and for the ALTER
I use a new OracleCommand for the SELECT than for the ALTER
I use the same OracleCommand for the SELECT and for the ALTER
I call PurgeStatementCache on the connection between the ALTER and SELECT
I call FlushCache on the connection between the ALTER and SELECT
I explicitly Close and Dispose the OracleCommand and OracleConnection (as opposed to the using block) used for the ALTER and SELECT
Restarted the calling PC and the PC hosting the Oracle database.
If I look at the column list by doing a SELECT * FROM all_tab_cols, the new column is there.
The only thing that seems to work reliably is closing the app and re-starting it (well it's from a unit test, but it's a shutdown and restart of the test host). Then I get that 4th column. Sometimes I can use breakpoints and re-execute queries and the 4th column will appear, but nothing that is specifically repeatable with straight execution of code (meaning without setting a break point and moving the execution point back up).
Something in the bowels of ODAC seems to be caching the schema of that table, but I can figure out what, why or how to prevent it. Anyone have any experience with this, or ideas how I might prevent it?
I know this answer comes years later but if new readers run into problems with caching try setting:
Metadata Pooling = false, Self Tuning = False and Statement Cache Size = 0
...in the connection string. Keep in mind that there are performance implications for doing so.
https://docs.oracle.com/database/122/ODPNT/featConnecting.htm#GUID-0CFEB161-68EF-4BC2-8943-3BDFFB878602
Maybe post some of your C# code. The following is a test that behaves as expected, meaning I can see the new column immediately after adding it. This is using odp 11.2 rel 5 hitting an 11g db, using 4.0 framework:
The test table is:
CREATE TABLE T1
(
DTE DATE default sysdate
);
Drop and recreate it after each run of the following C# code (a bit dirty but anyway):
string connStr = "User Id=xxx;Password=yyy;Data Source=my11gDb;";
using (OracleConnection con = new OracleConnection(connStr))
{
string s = "ALTER TABLE T1 ADD (added_col VARCHAR2(10))";
using (OracleCommand cmd = new OracleCommand(s, con))
{
con.Open();
cmd.ExecuteNonQuery();
string s2 = "select column_name from all_tab_columns where table_name = 'T1'";
//con.FlushCache(); // doesn't seem to matter, works with or without
using (OracleCommand cmd2 = new OracleCommand(s2, con))
{
OracleDataReader rdr = cmd2.ExecuteReader();
for (int i = 0; rdr.Read(); i++)
{
Console.WriteLine("Column {0} => {1}",i+1,rdr.GetString(0));
}
rdr.Close();
}
}
}
Output:
Column 1 => DTE
Column 2 => ADDED_COL
Edit:
Ah, ok, I see what you're saying, it looks like statement caching. I played around with changing the cache size to 0 (in conn string, use "Statement Cache Size=0"), and also tried cmd.AddToStatementCache = false, but these did not work.
One thing that does work is to use a slightly different string, like adding a space. I know its a hack, but this is all I can get to work for me anyway.
Try your example with:
var sql3 = "SELECT * FROM People";
var sql5 = "SELECT * FROM People "; // note extra space
And use sql3 before adding column, and sql5 after adding a column.
Hope that helps