How to modify a constraint on a SQL Server table from c#? - c#

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).

Related

how to create user define tables by ADO.net

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();
}
}

Updating Values with C# in SQL Table

I was wondering if it is possible for the update button to save the changes made in the table. I wrote this code but I have no idea how it could possibly work
This is the code i wrote for the update button:
string conString = "Data Source=MIRANDA-PC;Initial Catalog=Futebol do Rosa;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
string selectSql = "Update Players$ set Player Name='" + dataGridView2.Text + "";
SqlCommand cmd = new SqlCommand(selectSql, con);
con.Open();
This is the table I want to update the values in:
Well, you just need to execute your query with ExecuteNonQuery.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection and SqlCommand.
And if your table or column names more than one word, you need to use them with [] as [Player Name]. And honestly, it is a little bit weird to use $ sign in a table name.
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Update Players$ set [Player Name] = #name";
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
}
You have to execute your SQL query with your db object.
dbinstance.ExecuteSqlCommand(string sqlcommand, object[] params);
This method is both for DDL and DML.
you can also use ExecuteNonQuery method.
cmd.CommandText = "Update Players$ set [Player Name] = #Playername";
cmd.Parameters.Add("#Playername", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
The best solution (if possible) to to convert your DAL (Data Access Layer) to Entity-framework based, instead of writing your own SQL queries. This is safe-by-design and never is vulnerable to SQL Injection of any kind.
Here is some mockup code:
using (AppEntities currDb = new AppEntities)
{
Players PlayerToEdit =
from player in currDb.Players
where player.PlayerID == lngPlayerID
select player.First();
PlayerToEdit.PlayerName = dataGridView2.Text;
currDb.SaveChanges();
}
You can read about it some more here:
https://msdn.microsoft.com/en-us/data/ef.aspx

Generating SQL queries safely in C#

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..

Read\Write\Change MySql Table from asp.net list view

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.

ADO.Net : Get table definition from SQL server tables

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

Categories

Resources