so, i am building a new website for my brother and it seems that i need to use MySql for him.
In ASP.NET there is a list view item, that you can choose from which DB is will take the info and you can Read \ Write \ Change \ Delete with a click of a button.
any one here know how can i do that with MySql ? and not mssql.. i know how to use DataBases, i just didnt ever worked with MySql and i will be thankfull for anyone who will help me.
Thanks again! alon.. :)
You first need a connector which you can find here
Then instead of using System.Data classes use the one you just downloaded. They are the same classes, but the only difference is that they are for MySQL.
Furthermore if you want to write MySQL queries, well they are pretty much the same as in MSSQL. Here are some examples:
Read:
SELECT id, value FROM table
WHERE id = 16;
Write:
INSERT INTO table(id, value)
VALUES (1,'Bob'),(2,'Betty');
Change:
UPDATE table
SET id = 7
WHERE id = 16;
Delete:
DELETE FROM table
WHERE id = 7;
And in your C# code you just need to use 3-4 classes to work with the database. Since I don't want to make this a wall of text, you can read more about those classes here , unless you are familiar enough with those.
Here is a general approach to do basic operations with mysql database. I assume that you know how to setup your mysql database. if not you can find many info about it on google. I also assumed that you have a table on your mysql database named "table" which has following columns: id, name, address.
// Connection String
private const string ConnStr =
"Driver={MySQL ODBC 3.51 Driver};Server=localhost;" +
"Database=test;uid=root;pwd=;option=3";
// DataBinding
private void BindDataGrid()
{
using(OdbcConnection con = new OdbcConnection(ConnStr))
using(OdbcCommand cmd =
new OdbcCommand("SELECT * FROM Sample", con))
{
con.Open();
DataGrid1.DataSource = cmd.ExecuteReader(
CommandBehavior.CloseConnection |
CommandBehavior.SingleResult);
DataGrid1.DataBind();
}
}
// Insert Operation
private void InsertInfo()
{
if(CheckIsAddNameValid())
{
HtmlTable2.Visible = false;
using(OdbcConnection con = new OdbcConnection(ConnStr))
using(OdbcCommand cmd = new OdbcCommand("INSERT INTO sample" +
"(name, address) VALUES (?,?)", con))
{
cmd.Parameters.Add("#name", OdbcType.VarChar,
255).Value = TextBox3.Text.Trim();
cmd. Parameters.Add("#address", OdbcType.VarChar,
255).Value = TextBox4.Text.Trim();
con.Open();
cmd.ExecuteNonQuery();
BindDataGrid();
}
}
}
// Update Operation
private void UpdateInfo(int id, string name, string address)
{
using(OdbcConnection con = new OdbcConnection(ConnStr))
using(OdbcCommand cmd = new OdbcCommand("UPDATE sample " +
"SET name = ?, address = ? WHERE ID = ?", con))
{
cmd.Parameters.Add("#name", OdbcType.VarChar, 255).Value = name;
cmd.Parameters.Add("#address",
OdbcType.VarChar, 255).Value = address;
cmd.Parameters.Add("#ID", OdbcType.Int).Value = id;
con.Open();
cmd.ExecuteNonQuery();
}
}
// Update Operation
private void DeleteInfo(int id)
{
using(OdbcConnection con = new OdbcConnection(ConnStr))
using(OdbcCommand cmd = new OdbcCommand("DELETE " +
"FROM sample WHERE ID = ?", con))
{
cmd.Parameters.Add("#ID", OdbcType.Int).Value = id;
con.Open();
cmd.ExecuteNonQuery();
}
}
if you do not have a table on your database use this script to create the database in this example:
CREATE TABLE sample (
id int AUTO_INCREMENT NOT NULL,
name varchar(45) NOT NULL,
address varchar(45) NOT NULL,
PRIMARY KEY(id)
)
GO
BindDataGrid function shows the result of the query in datagrid. In general you can put the result of any query to a list and then bind it to the datagrid with the following code:
List<string> AllStudents = getAllStudents();
dataGrid1.datasource = AllStudents;
dataGrid1.databind();
ASP.Net works with database through the Provider Model. You you have downloaded the ADOconnector for MySql, it should work the same way as how it is with MS SQL, except that you have to use different set of queries specific to MySql.
You might also try looking into the Entity Framework. It is an object-relational-mapper (ORM) which abstracts the tables of a database into objects that you can easily work with in code. It makes code much more readable and maintainable than hardcoding SQL strings (as some of the other answers suggest).
The Entity Framework is Microsoft's recommended solution. You can use it with the MySQL connector that Bosak pointed out.
NHibernate is another popular ORM you might want to look into.
Related
I searched for an answer but the only solutions I found didn't work for SQLite.
I want to create different tables in my SQLite database with the name and columns defined by the user who creates the table.
I'm working on a project where users can test their knowledge of a language by creating a list that can be tested later. The list should be saved in a database as an apart table.
Image of the UI
So I want to save each list in the database with the table name equal to the "txtNaamLijst.Text" textbox.
Beside that I want the columns to have the name of "txtTaal1.Text" en "txtTaal2.Text" as defined by the user.
The script that I have written doesn't work. Scripts I found on the web did not work either. I have to write my SQLite commands in a single line because I use C#:
protected void btnSave_Click(object sender, EventArgs e)
{
using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db"))
{
using (System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(conn))
{
string naam = txtNaamLijst.Text;
string taal1 = txtTaal1.Text;
string taal2 = txtTaal2.Text;
string veld1 = txtVeld1.Text;
string veld1v2 = txtVeld1v2.Text;
string veld2 = txtVeld2.Text;
string veld2v2 = txtVeld2v2.Text;
string veld3 = txtVeld3.Text;
string veld3v2 = txtVeld3v2.Text;
string veld4 = txtVeld4.Text;
string veld4v2 = txtVeld4v2.Text;
string veld5 = txtVeld5.Text;
string veld5v2 = txtVeld5v2.Text;
string veld6 = txtVeld6.Text;
string veld6v2 = txtVeld6v2.Text;
conn.Open();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#naam", naam);
cmd.Parameters.AddWithValue("#taal1", taal1);
cmd.Parameters.AddWithValue("#taal2", taal2);
cmd.Parameters.AddWithValue("#veld1", veld1);
cmd.Parameters.AddWithValue("#veld1v2", veld1v2);
cmd.Parameters.AddWithValue("#veld2", veld2);
cmd.Parameters.AddWithValue("#veld2v2", veld2v2);
cmd.Parameters.AddWithValue("#veld3", veld3);
cmd.Parameters.AddWithValue("#veld3v2", veld3v2);
cmd.Parameters.AddWithValue("#veld4", veld4);
cmd.Parameters.AddWithValue("#veld4v2", veld4v2);
cmd.Parameters.AddWithValue("#veld5", veld5);
cmd.Parameters.AddWithValue("#veld5v2", veld5v2);
cmd.Parameters.AddWithValue("#veld6", veld6);
cmd.Parameters.AddWithValue("#veld6v2", veld6v2);
cmd.CommandText = "CREATE TABLE IF NOT EXISTS #naam (#taal1 VARCHAR(50), #taal2, VARCHAR(50))";
cmd.CommandText = "INSERT INTO #naam (#taal1, #taal2) SELECT #veld1 , #veld1v2 UNION ALL SELECT #veld2 , #veld2v2 UNION ALL SELECT #veld3 , #veld3v2 UNION ALL SELECT #veld4 , #veld4v2 UNION ALL SELECT #veld5 , #veld5v2 UNION ALL SELECT #veld6 , #veld6v2";
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();`
}
}
}
In both your queries you use #naam as the parameter for the table name.
cmd.CommandText = "CREATE TABLE IF NOT EXISTS #naam..."
cmd.CommandText = "INSERT INTO #naam..."
cmd.Parameters.AddWithValue("#naam", naam);
Unfortunately, parameterizing table names is not possible. User Soner Gönül put it well in this answer. He has quite a bit of information but the gist of it is:
You can not parameterize your table names, column names or any other databse objects. You can only parameterize your values.
Now, it is possible to use plain old string concentration/formatting to have a variable table name, but that is NOT a good idea, as it leaves you vulnerable to SQL injection.
A desktop-based software shall enable a user to create tables in a provided database as per requirement.
My problem is that ExecuteNonQuery treats only Data Manipulation Language.
What should i use for Data Definition Language, i.e to pass create command.
Thanks in advance :)
my code
3rd party edit
From the linked image
public void create(string name, int varchar_quantity, string rate)
{
con.Close();
string s = "Crate table anas('" + name + "' varchar ('"
+ varchar_quantity + "')" + rate + "' int);";
con.Open();
SqlCommand com = new SqlCommand(s, con);
com.ExecuteNonQuery();
}
You should be able to create tables with ExecuteNonQuery method.
From msdn documentation,
You can use the ExecuteNonQuery to perform catalog operations (for
example, querying the structure of a database or creating database
objects such as tables), or to change the data in a database without
using a DataSet by executing UPDATE, INSERT, or DELETE statements.
var conStr = "PUT YOUR CONNECTION STRING HERE";
using (var c = new SqlConnection(conStr))
{
c.Open();
var qry = "CREATE TABLE TEST(name varchar(30));";
using (var cmd = new SqlCommand(qry, c))
{
cmd.ExecuteNonQuery();
}
}
I want to modify a constraint on a SQL Server table from C# code. Is it possible to do?
Please help.
Here is a sample code for update that I use.
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "UPDATE Student(LastName, FirstName, Address, City)
VALUES(#ln, #fn, #add, #cit) WHERE LastName='" + lastName + "' AND FirstName='" + firstName+"'";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
var removeConstraint = "ALTER TABLE Customer DROP CONSTRAINT Con_First;";
var createConstraint = "ALTER TABLE Customer ADD CONSTRAINT Con_First UNIQUE (Address);";
var removeConstraintCmd = new SqlCommand(removeConstraint, conn);
removeConstraintCmd.ExecuteNonQuery();
var createConstraintCmd = new SqlCommand(createConstraint, conn);
createConstraintCmd.ExecuteNonQuery();
NOTE: conn is your connection
The script strings (top two variables) will be what you need to change but, in summary, you drop the constrain then recreate it.
As a side note, I'd be curious to see why you want to do this. You may have problems in your overall approach as this is not something typically done from ADO .net (depending on your scenario of course).
What's the safest way of generating SQL queries in C#, including cleansing user input so it's safe from injection? I'm looking to use a simple solution that doesn't need external libraries.
Use Sql Parameters:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter(v=vs.80).aspx
Here's an example in C#
SqlCommand tCommand = new SqlCommand();
tCommand.Connection = new SqlConnection("YourConnectionString");
tCommand.CommandText = "UPDATE players SET name = #name, score = #score, active = #active WHERE jerseyNum = #jerseyNum";
tCommand.Parameters.Add(new SqlParameter("#name", System.Data.SqlDbType.VarChar).Value = "Smith, Steve");
tCommand.Parameters.Add(new SqlParameter("#score", System.Data.SqlDbType.Int).Value = "42");
tCommand.Parameters.Add(new SqlParameter("#active", System.Data.SqlDbType.Bit).Value = true);
tCommand.Parameters.Add(new SqlParameter("#jerseyNum", System.Data.SqlDbType.Int).Value = "99");
tCommand.ExecuteNonQuery();
In essence don't do this
SqlCommand command = new SqlCommand(MyConnection);
command.CommandText = "Select * From MyTable Where MyColumn = '" + TextBox1.Text + "'"
...
do
SqlCommand command = new SqlCommand(MyConnection);
command.CommandText = "Select * From MyTable Where MyColumn = #MyValue";
command.Parameters.AddWithValue("MyValue",TextBox1.Text);
...
Basically never build your sql command directly from user input.
If you use an ORM, such as EntityFrameworks / POCO all queries are done in the latter form.
The first rule of thumb is to make sure you use parameterized queries/commands. Basically don't dynamically build a sql string that includes something that the user has input into the page.
If you use on ORM (EF, L2S, Nhib), this is typically handled in most cases because most all of them run parameterized queries.
Parametrize your queries.
In case if you build some TSQL which builds some other dynamic TSQL - then use some described technique
What does "parametrizing means?
See, not use something like this:
sqlCommand.CommandText = "select * from mytable where id = "+someVariable;
use this:
sqlCommand.CommandText = "select * from mytable where id = #id";
sqlCommand.Parameters.AddWithValue("#id", someVariable);
Make use of Parametrized Queries.
Simple Example.
var sql = "SELECT * FROM MyTable WHERE MyColumn = #Param1";
using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#Param1", param1Value);
return command.ExecuteReader();
}
More Detailed Example.
protected void btnGoodAddShipper_Click(object sender, EventArgs e)
{
string connStr = c
"Server=(local);Database=Northwind;Integrated Security=SSPI";
// this is good because all input becomes a
// parameter and not part of the SQL statement
string cmdStr =
"insert into Shippers (CompanyName, Phone) values (" +
"#CompanyName, #Phone)";
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
// add parameters
cmd.Parameters.AddWithValue
("#CompanyName", txtCompanyName.Text);
cmd.Parameters.AddWithValue("#Phone", txtPhone.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Using DBML and LINQ to handle it for you. Many people have worked on those to ensure those issues are well mitigated.
And if not than at least parametrize your queries.
A proper name for DBML is linq2sql or an advanced version is called entity framework. These technologies are provided by Microsoft and well integrated with visual studio. Does not require additional libraries.
Pretty stable products..
I am using C# to write a method that returns the following information about a table:
column names, column types, column sizes, foreign keys.
Can someone point me in the right direction on how to accomplish this ?
This really depends on how you communicate with your database. If you are using LinqToSQL or another similar ORM this would be pretty easy but if you want to get these values via a query I'd suggest you use the INFORMATION_SCHEMA views as these are fast and easy to query.
e.g.
select * from information_schema.columns where table_name = 'mytable'
To get the FK and Schema you should be able to use:
DA.FillSchema()
DS.Table("Name").PrimaryKey
OR calling sp_fkey using the method demonstrated below
Code Snippet from AND Another Link
private void LoanSchema()
{
private List<String> tablesList = new List<String>();
private Dictionary<String, String> columnsDictionary = new Dictionary<String, String>();
string connectionString = "Integrated Security=SSPI;" +
"Persist Security Info = False;Initial Catalog=Northwind;" +
"Data Source = localhost";
SqlConnection connection = new SqlConnection();
connection.ConnectionString = connectionString;
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "exec sp_tables";
command.CommandType = CommandType.Text;
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
tablesList.Add(reader["TABLE_NAME"].ToString());
}
reader.Close();
command.CommandText = "exec sp_columns #table_name = '" +
tablesList[0] + "'";
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
columnsDictionary.Add(reader["COLUMN_NAME"].ToString(), reader["TYPE_NAME"].ToString());
}
}
You can use the SqlDataAdapter.FillSchema() method.
Alternatively you can use the SqlDataAdapter.Fill() method after setting the MissingSchemaAction property of the SqlDataAdapter to AddWithKey. But if you only want the schema you must ensure that your query returns no rows. This can be accomplished by adding a statement like WHERE 1=2 to your query.
If you are using MS SQL Server then You should definately have a look at SMO namespace (server management objects).
There are objects which You can use in .net responsible for all kinds of things in a database (including but not limited to tables, columns, constraints etc.)
I think you need the System.Data.DataTable class:
http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx