0% found this document useful (0 votes)
3 views2 pages

SQL Database Example in C#

Uploaded by

slsmgmccsit
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

SQL Database Example in C#

Uploaded by

slsmgmccsit
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

In the following example, we create a database table and fill it with

data using sql.


using [Link];

namespace CreateTable
{
class Program
{
static void Main(string[] args)
{
var cs = @"Server=localhost\
SQLEXPRESS;Database=testdb;Trusted_Connection=True;";

using var con = new SqlConnection(cs);


[Link]();

using var cmd = new SqlCommand();


[Link] = con;

[Link] = "DROP TABLE IF EXISTS cars";


[Link]();

[Link] = @"CREATE TABLE cars(


id int identity(1,1) NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price INT
)";
[Link]();

[Link] = "INSERT INTO cars(name, price)


VALUES('Audi',52642)";
[Link]();

[Link] = "INSERT INTO cars(name, price)


VALUES('Mercedes',57127)";
[Link]();

[Link] = "INSERT INTO cars(name, price)


VALUES('Skoda',9000)";
[Link]();

[Link] = "INSERT INTO cars(name, price)


VALUES('Volvo',29000)";
[Link]();

[Link] = "INSERT INTO cars(name, price)


VALUES('Bentley',350000)";
[Link]();

[Link] = "INSERT INTO cars(name, price)


VALUES('Citroen',21000)";
[Link]();
[Link] = "INSERT INTO cars(name, price)
VALUES('Hummer',41400)";
[Link]();

[Link] = "INSERT INTO cars(name, price)


VALUES('Volkswagen',21600)";
[Link]();

[Link]("Table cars created");


}
}
}

In the following example we print column headers with the data


from a database table.
using [Link];

namespace ColumnHeaders
{
class Program
{
static void Main(string[] args)
{
string cs = @"Server=localhost\
SQLEXPRESS;Database=testdb;Trusted_Connection=True;";

using var con = new SqlConnection(cs);


[Link]();

var sql = "SELECT * FROM cars";


using var cmd = new SqlCommand(sql, con);

using SqlDataReader rdr = [Link]();


[Link]($"{[Link](0),-4} {[Link](1),-10}
{[Link](2),10}");

while ([Link]())
{
[Link]($"{rdr.GetInt32(0),-4} {[Link](1),-
10} {rdr.GetInt32(2),10}");
}
}
}
}

You might also like