Insert foreign key into table with SQL query using C# - c#

I have a database with 3 tables Identification, Identification_group and Group.
The Identification_group table has 2 foreign key columns, Identificaiton_id and Group_id.
In my form you can select the Group Number and it returns the right Group_id to the Identification_group table.
Is it possible to write a SQL query that uses the last Identification_id and the Group_id (from the selection field in my form) and writes this to the Identification_group table?
string sqlquery1 = "Insert into [dbo].[identification_group] (fk_group_id,fk_identification_id values (#fk_group_id,#fk_identification_id;";
SqlCommand schreiben = new SqlCommand(sqlquery1, myConnection);
myConnection.Open();
schreiben.Parameters.AddWithValue("#fk_identification_id", intidentification_id);
schreiben.Parameters.AddWithValue("#fk_group_id", Wil_Jls_idComboBox.SelectedValue);
schreiben.CommandText = sqlquery;
schreiben.ExecuteNonQuery();
myConnection.Close();
Sorry for the bad formatting, first time posting here.
Thank you in advance

Please try the below:
You have an issue with your SQL statement whereby you did not close the brackets. Also, you only need the # symbol in the SQL statement, and not in the C# code.
// Create the query
string query = "Insert into [identification_group] (fk_group_id, fk_identification_id) values (#fk_group_id, #fk_identification_id)";
// Create the SQL command
SqlCommand schreiben = new SqlCommand(query, myConnection);
// Open the SQL connection
myConnection.Open();
// Bind the parameters
schreiben.Parameters.AddWithValue("fk_identification_id", intidentification_id);
schreiben.Parameters.AddWithValue("fk_group_id", Wil_Jls_idComboBox.SelectedValue);
// Bind the command
schreiben.CommandText = query;
// Execute the command
schreiben.ExecuteNonQuery();
// Close the connection
myConnection.Close();

Related

Database Handling in C#

I'm having some problems on my application since I'm not very experienced on the database handling, so far I've created my database with a table, and what I wanted to do is to show a specific data from the table as a variable.
My application has to do with chemical elements, therefore the table "elements" has all of them. I was thinking of making a random element generator using a random number to get any of the elements in the table with a query or something.
Random ra = new Random();
int random_anumber = ra.Next(1, 9);
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Francisco\Documents\FormData.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM elements", con);
I was thinking on putting the random_anumber instead of the "*" but it's still not showing a single element. Since I don't know how to show them of convert the data into a variable.
The "*" in the SQL statement is a field name selector and not a filter. So changing the * to something else won't limit your query to a single element. You have to add a where clause for that.
To solve this you can either use the SqlDataAdapter onto a DataSet and use the DataTable within the DataSet to grab a random row by using the random number as the index or run a simple query. I recommend running a query if all you need to do with this data is display a random element.
--- Update ---
MS SQL Server Statement:
SELECT TOP 1 * FROM table
ORDER BY NEWID()
MySQL Statement:
SELECT * FROM table
ORDER BY RAND()
LIMIT 1
The * is a wildcard character that select all columns/fields of the table. You can change the to a comma delimited list of columns/fields you want to retrieve from the database.
Hope that the Table elements having a unique Key Field(let it be element_id) then you can access the Random Element by Specifying the ID in the Where Clause, Then your Query will be like The following:
string querySQL="SELECT * FROM elements Where element_id=#id";
SqlCommand cmd = new SqlCommand(querySQL, con) // con is the Connection
cmd.Parameters.AddWithValue("#id", random_anumber);
// Get data using Adapter
This is how I do it everyday:
Note: Here you can see that I use Sqlite in my example. You can use SQL by removing the Lites and using the right classes in SQL respectively.
string ConnectionString = "data source={0}; initial catalog={1}; integrated security=true; application name= <Your App Name>" providerName="System.Data.SqlClient";
string DatabasePath = "<Your Path to your database>";
string commandstring = "SELECT * FROM elements";
using (SQLiteCommand MyCommand = new SQLiteCommand(commandstring, Connection))
{
using (SQLiteDataReader MyReader = MyCommand.ExecuteReader())
{
while (MyReader.Read())
{
// Here is your result:
// You can do anything that you want with it.
// The 0 shows the first column. If your result returns more than one column, //you can use other numbers like 1,2..n to get other columns out of your data //reader.
MyReader.GetString(0);
}
}
}`

Finding out through SQL or OLEDB which of an Access tables' columns is autoincremented?

I need to find all the multiple or non-autoincremented primary keys, make them normal keys, and make the primary key an autoincrement column. But I need to check if there is already an autoincrement column, so I make that one a primary key, in case if it's not.
Based on this Microsoft article on How To Retrieve Column Schema by Using the DataReader GetSchemaTable Method and Visual C# .NET I have written a little code for you to pick the field with the auto increment set to True,
OleDbConnection cn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
DataTable schemaTable;
OleDbDataReader myReader;
//Open a connection to the SQL Server Northwind database.
cn.ConnectionString = "...";
cn.Open();
//Retrieve records from the Employees table into a DataReader.
cmd.Connection = cn;
cmd.CommandText = "SELECT * FROM Employees";
myReader = cmd.ExecuteReader(CommandBehavior.KeyInfo);
//Retrieve column schema into a DataTable.
schemaTable = myReader.GetSchemaTable();
var myAutoIncrements = schemaTable.Rows.Cast<DataRow>().Where(
myField => myField["IsAutoIncrement"].ToString() == "True");
foreach (var myAutoInc in myAutoIncrements)
{
Console.WriteLine((myAutoInc[0]));
}
Console.ReadLine();
//Always close the DataReader and connection.
myReader.Close();
cn.Close();
You can simply paste this on you app or even a new console app and see the results of shown Fields with the IsAutoIncrement set to true.
OleDbReader has a GetSchemaTable method. You can call that with a basic select to each table, then loop through the returned columns and check for IsAutoIncrement.
https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.getschematable(v=vs.110).aspx

Syntax error while trying to fetch data from MySql

So I am trying to fetch a value from the database, selecting the row using WHERE INT.
conn = new MySqlConnection(DBdetails.connStr);
conn.Open();
query = "SELECT * FROM tables WHERE table=#tafel";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#tafel", tafel);
cmd.ExecuteNonQuery();
However it wont pass 'cmd.ExecuteNonQuery()', it throws a error saying the syntax isnt right like: "near table=1", "near table=2"
I tried fetching a other one in the same table that is a var char and it worked perfectly.
Don't really see what I am doing wrong. The 'table' column is a int and 'tafel' is a int to.
Thanks!
Put your field name table in backticks (table is a reserved word in MySQL) :
query = "SELECT * FROM `tables` WHERE `table` = #tafel";
As others said, table is a reserved word in MySQL. You need to use quote with it like
query = "SELECT * FROM tables WHERE `table` = #tafel";
However, the best solution is to change the name to a nonreserved word.
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection conn = new MySqlConnection(DBdetails.connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM tables WHERE `table` = #tafel";
cmd.Parameters.AddWithValue("#tafel", tafel);
conn.Open();
cmd.ExecuteNonQuery();
}
By the way, I don't understand why you use ExecuteNonQuery with SELECT statement. It just executes your query. It doesn't even return any value.
If you want to get the result of your query, you can use ExecuteReader method which returns SqlDataReader as your result rows.

SQL Server database last_rowID

I have a C# app with have to use SQL Server database with 1 table (All_Data) and 5 columns (ID, Name, Surename, Age,Location)
Before inserting a new row how can I find out or get the value of the last ID in the table
I have a following code but it,a not work well
string query = "SELECT MAX(ID) FROM All_Data";
SqlCommand comSelect;
comSelect = new SqlCommand(query, connection);
int ID = (int)comSelect.ExecuteScalar();
ERROR message:
ExecuteScalar: Connection property has not been initialized
Please help me
First, from your code it is not clear what is the value of the variable connection.
From the error message it seems that you don't have initialized this variable and thus you get the error. (connection = new SqlConnection(....);)
However, this is not the correct way to handle this scenario.
You need to make the ID column an IDENTITY column and then don't try to retrieve its value before executing any INSERT.
An IDENTITY column receives its value directly from the database when there is a new record to insert. And letting the database code work on this data it is the best option if you want to be safe from concurrency issues.
If you need to retrieve the ID value after an INSERT query because you need it as a Foreign Key in other tables or for your own code, then you could simply use the T-SQL command
SELECT SCOPE_IDENTITY()
For example, suppose you have to insert a record in that table, and you want to know the IDENTITY value assigned to the ID column
string query = #"INSERT INTO All_Data(Name,Surename,Age,Location)
VALUES(#name, #surname, #age, #loc);
SELECT SCOPE_IDENTITY()";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
cmd.Parameters.AddWithValue("#name", yourNameValue);
.... other parameters ...
int newID = Convert.ToInt32(cmd.ExecuteScalar());
}
As you can see, this code doesn't try to pass a value for the ID column. It pass just the other fields with a parameterized query. But at the end of the first query there is a call to SELECT SCOPE_IDENTITY() and this returns whatever value the database has assigned to the column ID (of course you should have set the IDENTITY property on the field).
This will work correctly in multiuser and concurrent scenario
The error fires when the command doesn't have a connection. Please check connection is open.
Error saysExecuteScalar: Connectio property has not been initialized
double Check your connection string whether it is defined properly. You can check here to know how to define connection string.
you have not opened connection so open it before use :
comSelect = new SqlCommand(query, connection);
connection.Open();
int ID = (int)comSelect.ExecuteScalar();
connection.Close();

MySQL truncate command with parameter not working

Why do I get an exception when trying to truncate a MySQL table (using MySQL Connector/Net)? I am trying to give the table name with a parameter.
This is the code I'm executing:
var connectionString = "Server="+_server+";Uid="+_user+";Pwd="+_password+";Database="+_database+";";
try
{
using (var conn = new MySqlConnection(connectionString))
{
conn.Open();
const string sql = "TRUNCATE TABLE #tablename"; // also tried with TRUNCATE #tablename
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#tablename", "test");
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (MySqlException ex)
{
Console.WriteLine(ex.ToString());
}
And this is the execption:
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error
in your SQ L syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near ''test'' at line 1
When I try a select query, for example, then I don't have any problems. This runs fine and returns correct data:
conn.Open();
const string sql = "SELECT body FROM test WHERE id=#pid";
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#pid", 1);
cmd.ExecuteScalar();
conn.Close();
Parameters are used for query values, not object names like tables.
So this will not work for sure.
You need to set the table name in the command string by using string concatenation. You can avoid sql injection attacks by manually checking for weird characters in the table name (spaces, dashes, semicolons, etc..)
I've been playing around with this for a while now, and i can't seem to get it to work either. I can't find any documentation online, so i'm starting to think you may not be able to truncate with a parameter like you've tried.
However, is there really a need to prevent SQL injection on this command? Does the user enter the name of the table they want to truncate, and if so, they're just going to truncate a table which...is essentially what the command does anyway?

Categories