Checking and creating a View within MySQL via C# - c#

I need to be able to see if a View already exists within my MySQL database and if it doesn't create one - through c#. I really could do with a bit of help and a point in the right direction - if possible.

You can use information_schema to query if a sever object, view in your case, exists. My example code snippet in C# is as below.
String conn = #"Data Source=myserverName;
Initial Catalog=myCatalogName;Integrated Security=True";
string cmdStr = "select count(*) from
information_schema.views where table_schema = 'mySchemaName'
AND table_name = 'MyViewName'";
using (MySqlConnection conn = new MySqlConnection(conn))
{
MySqlCommand cmd = new MySqlCommand(cmdStr, conn);
conn.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int count = reader.GetInt32(0);
if (count == 0)
{
MessageBox.Show("View does not exists!");
MySqlCommand command = new MySqlCommand("Create View myView
as select
* from myTable;", conn)
command.ExecuteNonQuery();
}
else if (count == 1)
{
MessageBox.Show("View exists!");
}
conn.Close();
}
}

Can't you use create or replace view view_name as... ?

Related

Why does my MySQL connection not work in visual studio code C#?

i am making a program in visual studio code with C#, it is a paid program so it needs an hwid system. Basically i want it to check if your computer HWID exists in the HWID table in my users database. But it says it can't connect to the database. Can you help me? This is my code.`
string connectionString = "Server=SomeServer;Database=i got you this is notthe real database;User ID=same;Password=same for password;";
MySqlConnection mydbCon = new MySqlConnection(connectionString);
mydbCon.Open();
MySqlCommand command = mydbCon.CreateCommand();
command.CommandText = "SELECT * FROM yourTable WHERE hwid = GetHDDSerial";
IDataReader reader = command.ExecuteReader();
`
It could be that the connection string isn't formatted the way the MySQL connector wants it. The MySQL documentation shows "uid" instead of User, and "pwd" instead of Password. https://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-connection-string.html
This should do what you need:
string connectionString = "Server=SomeServer;Database=i got you this is notthe real database;User ID=same;Password=same for password;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand())
{
string sql = "SELECT * FROM yourTable WHERE hwid = #val1";
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Parameters.AddWithValue("#val1", "GetHDDSerial");
connection.Open();
using (MySqlDataAdapter adapter = new MySqlDataAdapter())
{
using (DataSet ds = new DataSet())
{
adapter.SelectCommand = command;
adapter.Fill(ds);
if (ds.Tables.Count > 0)
{
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
// Do something here. You can access the data like this:
// row["Id"] or whatever your field names are.
// int id = (int) row["Id"];
// Of course, I don't know your field names, so you'll have to complete this.
}
}
}
}
}
}

windows service integration with sql using ado .net

**public static void göster()
{
SqlConnection connection =GetConnection.GetConnectionObject();
//TODO parametreleri command.parameters yoluyla alsın
SqlCommand command = new SqlCommand();
command.CommandText= "select * from windowsserv";
command.Connection = connection;
if (connection.State != ConnectionState.Open)
connection.Open();
Console.WriteLine("Connection opened");
SqlDataReader rdr = command.ExecuteReader();
while(rdr.Read())
{
------------------> Console.WriteLine(rdr[0].ToString()+"--"+rdr[1].ToString());
}
if (connection.State != ConnectionState.Closed)
connection.Close();
Console.WriteLine("Connection Closed.");
Console.ReadLine();
}
Hi all, This is my code and also there are more that ı didn't show,I recorded data to sql server. This code block(pointed with arrow) shows all sql server data and ı want to see only last data (recorded to sql server) in console. But ı could't find any answer. Please help.**
In this line
command.CommandText= "select * from windowsserv";
you can use some SQL Filters and Ordering, like: (This will return last 10 register based on a date filter.. now you need to know what range your (last data) has been recorded to get exactly what you need.
Replace (date_column) with a column in your table who have this kind of data.
select top 10 * from windowsserv where (date_column) between '2017-09-12 00:00:00' and '2017-09-13 00:00:00' order by (date_column) DESC
Then in your code you will have something like this:
SqlCommand command = new SqlCommand();
command.CommandText = "select * from select top 10 * from windowsserv where (date_column) between \'2017-09-12 00:00:00\' and \'2017-09-13 00:00:00\' order by (date_column) DESC";
You can improve your code as well doing this:
using (SqlConnection connection = GetConnection.GetConnectionObject())
{
//TODO parametreleri command.parameters yoluyla alsın
var command = new SqlCommand
{
CommandText = "select * from windowsserv",
Connection = connection
};
if (connection.State != ConnectionState.Open)
connection.Open();
Console.WriteLine("Connection opened");
var rdr = command.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0] + "--" + rdr[1]);
}
}
try changing your while loop to.
bool isLast = rdr.Read();
while(isLast)
{
string firstCol = rdr[0].ToString();
string secondCol = rdr[1].ToString();
isLast = rdr.Read();
if(!isLast)
{
Console.WriteLine(firstCol+"--"+secondCol);
break;
}
}

Second result of select query in Mysql c#

I can`t to return value from second query.
Part of code...
MySqlConnectionStringBuilder mysqlSB = new MySqlConnectionStringBuilder();
mysqlSB.Server = "localhost";
mysqlSB.Database = "test";
mysqlSB.UserID = "admin";
mysqlSB.Password = "1111";
MySqlConnection con = new MySqlConnection();
con.ConnectionString = mysqlSB.ConnectionString;
MySqlCommand Select = new MySqlCommand("select name from table_1 where id='1' ", con);
MySqlDataReader myReader;
con.Open();
myReader = Select.ExecuteReader();
while (myReader.Read())
{
count++;
}
string name = myReader["name"].ToString();
if (count == 1)
{
MySqlCommand Select2 = new MySqlCommand("select country from table_2 where name='"+name+"'", con);
MySqlDataReader myReader2;
myReader2 = Select2.ExecuteReader();
while (myReader2.Read())
{
count++;
}
return myReader2["id"].ToString();
}
If I delete second part, after if(count==1) and return name = all ok, but when I return id will error. Plase Tell why, because I need to return second, third... values of query.
Thank you!
If I were you I'd fill a datatable with the results of your query
See here
Connecting to a Mysql DB with C# - Need some with Datasets
I don't know what you want to do with the countries you select out but if its in a datatable you can then bind it to a dropdown or something
In your second you are returning id field and are only selecting the country field from the database. It isn't returning an id field for you to read from thus an error.

using the same instance of SQLCommand more than one time in the same code for more than one query?

I have question about using why i can not use the same instance of SQLCommand more than one time in the same code?
I tried the code down here and it runs good for the gridview but when i changed the query by using cmd.CommandText() method it keeps saying:
There is already an open DataReader associated with this Command which must be closed first.
This is the code:
string cs = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "Select top 10 FirstName, LastName, Address, City, State from Customers";
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
cmd.CommandText = "SELECT TOP 10 COUNT(CreditLimit) FROM Customers";
int total = (int)cmd.ExecuteScalar();
TotalCreditLble.Text = "The total Credit :" + total.ToString();
}
catch(Exception exp)
{
Response.Write(exp.Message);
}
finally
{
con.Close();
}
The problem is that you are using the SqlCommand object to generate a DataReader via the command.ExecuteReader() command. While that is open, you can't re-use the command.
This should work:
using (var reader = cmd.ExecuteReader())
{
GridView1.DataSource = reader;
GridView1.DataBind();
}
//now the DataReader is closed/disposed and can re-use command
cmd.CommandText = "SELECT TOP 10 COUNT(CreditLimit) FROM Customers";
int total = (int)cmd.ExecuteScalar();
TotalCreditLble.Text = "The total Credit :" + total.ToString();
There is already an open DataReader associated with this Command which must be closed first.
This is the very reason you don't share a command. Somewhere in your code you did this:
cmd.ExecuteReader();
but you didn't leverage the using statement around the command because you wanted to share it. You can't do that. See, ExecuteReader leaves a connection to the server open while you read one row at a time; however that command is locked now because it's stateful at this point. The proper approach, always, is this:
using (SqlConnection c = new SqlConnection(cString))
{
using (SqlCommand cmd = new SqlCommand(sql, c))
{
// inside of here you can use ExecuteReader
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// use the reader
}
}
}
These are unmanaged resources and need to be handled with care. That's why wrapping them with the using is imperative.
Do not share these objects. Build them, open them, use them, and dispose them.
By leveraging the using you will never have to worry about getting these objects closed and disposed.
Your code, written a little differently:
var cs = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
var gridSql = "Select top 10 FirstName, LastName, Address, City, State from Customers";
var cntSql = "SELECT TOP 10 COUNT(CreditLimit) FROM Customers";
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand(gridSql, con))
{
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
using (SqlCommand cmd = new SqlCommand(cntSql, con))
{
int total = (int)cmd.ExecuteScalar();
TotalCreditLble.Text = "The total Credit :" + total.ToString();
}
}
catch(Exception exp)
{
Response.Write(exp.Message);
}
}
Thank u quys but for the guys who where talking about using block !
why this code work fine which i seen it on example on a video ! It's the same thing using the same instance of SqlCommand and passing diffrent queries by using the method CommanText with the same instance of SqlCommand and it's execute just fine , this is the code :
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "Delete from tbleProduct where ProductID= 4";
int TotalRowsAffected = cmd.ExecuteNonQuery();
Response.Write("Total rows affected :" + TotalRowsAffected );
cmd.CommandText = "Insert into tbleProduct values (4, 'Calculator', 100, 230)";
TotalRowsAffected = cmd.ExecuteNonQuery();
Response.Write("Total rows affected :" + TotalRowsAffected );
cmd.CommandText = "ypdate tbleProduct set QtyAvailbe = 234 where ProductID = 2";
TotalRowsAffected = cmd.ExecuteNonQuery();
Response.Write("Total rows affected :" + TotalRowsAffected );
}

How to parameterise table name in ODBC query

I have an ODBC connection to a database and I would like the user to be able to view data within any table. As this is an ASP.net application I cannot trust that the table name sent doesn't also contain nasties. I have tried using a parameterised query but I always get an error saying that I "Must declare the table variable" - this appears to be an issue because it is the table name
string sql = "SELECT TOP 10 * FROM ? ";
OdbcCommand command = new OdbcCommand(sql, dbConnection);
command.Parameters.Add(new OdbcParameter("#table", tableName));
OdbcDataAdapter adapter = new OdbcDataAdapter();
adapter.SelectCommand = command;
adapter.Fill(tableData);
What is the best method to achieve this in a secure way?
Use a stored procedure, it's the safest way.
Some hints:
You probably may also use the System.Data.SqlClient namespace objects
Enclose your connection, command and adapter objects initializations in using statements
Here's a simple example:
string sqlStoredProcedure = "SelectFromTable";
using (OdbcConnection dbConnection = new OdbcConnection(dbConnectionString))
{
dbConnection.Open();
using (OdbcCommand command = new OdbcCommand(sqlStoredProcedure, dbConnection))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.Add(new OdbcParameter("#table", tableName));
using (OdbcDataAdapter adapter = new OdbcDataAdapter(command))
{
adapter.SelectCommand = command;
adapter.Fill(tableData);
}
}
}
Another way to go would be to retrieve all table names and validate the tableName string variable as an entry in the list, maybe using:
DataTable tables = dbConnection.GetSchema(OdbcMetaDataCollectionNames.Tables);
Here's a simple implementation based on your scenario:
string sql = "SELECT TOP 10 * FROM {0}";
using (OdbcConnection dbConnection = new OdbcConnection(dbConnectionString))
{
dbConnection.Open();
DataTable tables = dbConnection.GetSchema(OdbcMetaDataCollectionNames.Tables);
var matches = tables.Select(String.Format("TABLE_NAME = '{0}'", tableName));
//check if table exists
if (matches.Count() > 0)
{
using (OdbcCommand command = new OdbcCommand(String.Format(sql, tableName), dbConnection))
{
using (OdbcDataAdapter adapter = new OdbcDataAdapter(command))
{
adapter.SelectCommand = command;
adapter.Fill(tableData);
}
}
}
else
{
//handle invalid value
}
}

Categories

Resources