Skip to content

Commit

Permalink
SqlCommand
Browse files Browse the repository at this point in the history
  • Loading branch information
XuanThuLab committed Aug 23, 2020
1 parent a4a4257 commit 6f779cb
Show file tree
Hide file tree
Showing 11 changed files with 287 additions and 0 deletions.
Binary file modified .DS_Store
Binary file not shown.
27 changes: 27 additions & 0 deletions MSSQL/ADO_02_SqlCommand/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/netcoreapp3.1/ADO_02_SqlCommand.dll",
"args": [],
"cwd": "${workspaceFolder}",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
42 changes: 42 additions & 0 deletions MSSQL/ADO_02_SqlCommand/.vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/ADO_02_SqlCommand.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/ADO_02_SqlCommand.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"${workspaceFolder}/ADO_02_SqlCommand.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
]
}
12 changes: 12 additions & 0 deletions MSSQL/ADO_02_SqlCommand/ADO_02_SqlCommand.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="System.Data.SqlClient" Version="4.8.1" />
</ItemGroup>

</Project>
16 changes: 16 additions & 0 deletions MSSQL/ADO_02_SqlCommand/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;

namespace SqlCommandExam
{
partial class Program
{
static void Main(string[] args)
{
// CreateSqlCommand01();
// InsertNewShipper();
// InsertNewShipperExecuteNonQuery();
// ReadCategory();
CallStoredProcedure();
}
}
}
6 changes: 6 additions & 0 deletions MSSQL/ADO_02_SqlCommand/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
```
dotnet add package System.Data.SqlClient
```

https://xuanthulab.net/ado-net-sqlcommand-truy-van-va-cap-nhat-du-lieu-c-sql-server.html

43 changes: 43 additions & 0 deletions MSSQL/ADO_02_SqlCommand/callProcedure.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlCommandExam
{
public partial class Program
{
public static void CallStoredProcedure()
{
string sqlconnectStr = "Data Source=localhost,1433;Initial Catalog=xtlab;User ID=SA;Password=Password123";
SqlConnection connection = new SqlConnection(sqlconnectStr);
connection.Open();

// Thi hành thủ tục PROCEDURE [dbo].[getproduct](@id int) trong MS SQL Server
SqlCommand cmd = new SqlCommand("getproduct", connection);
cmd.CommandType = CommandType.StoredProcedure;
// Tham số của procedure
cmd.Parameters.Add(
new SqlParameter() {
ParameterName = "@id",
SqlDbType = SqlDbType.Int,
Value = 10
}
);

// Đọc kết quả trả về
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var ten = reader["TenSanpham"];
var gia = reader["Gia"];

Console.WriteLine($"{ten} \t {gia}");
}
}


connection.Close();
}
}
}
37 changes: 37 additions & 0 deletions MSSQL/ADO_02_SqlCommand/createSqlCommad1.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlCommandExam {
public partial class Program {
public static void CreateSqlCommand01 () {

// Mở kết nối đến SQL Server
string sqlconnectStr = "Data Source=localhost,1433;Initial Catalog=xtlab;User ID=SA;Password=Password123";
SqlConnection connection = new SqlConnection (sqlconnectStr);
connection.Open ();

string queryString = "SELECT TenDanhMuc, MoTa FROM Danhmuc";
using (SqlCommand cmd = new SqlCommand (queryString, connection)) {
// Mã sử dụng SqlCommand ở đây
// Thiết lập tham số cmd cmd.Parameters nếu cần thiết
// Thi hành lệnh (như ) cmd.ExecuteReader(); ...
using (SqlDataReader reader = cmd.ExecuteReader ()) {
// Đoạn này đọc dữ liệu do SqlCommand trả về, đọc ở phần sau
DataTable myTable = new DataTable ();
myTable.Load (reader);
foreach (DataRow dataRow in myTable.Rows) {
foreach (var item in dataRow.ItemArray) {
Console.Write ($"{item} ");
}
Console.WriteLine ();
}

}
}
// Đóng kết nối khi không còn dùng
connection.Close ();

}
}
}
34 changes: 34 additions & 0 deletions MSSQL/ADO_02_SqlCommand/insertShipper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlCommandExam
{
public partial class Program
{
public static void InsertNewShipper()
{
// Mở kết nối MS SQL Server
string sqlconnectStr = "Data Source=localhost,1433;Initial Catalog=xtlab;User ID=SA;Password=Password123";
SqlConnection connection = new SqlConnection(sqlconnectStr);
connection.Open();

// Câu truy vấn gồm: chèn dữ liệu vào và lấy định danh(Primary key) mới chèn vào
string queryString = @"INSERT INTO Shippers (Hoten, Sodienthoai) VALUES (@Hoten, @Sodienthoai);
SELECT CAST(scope_identity() AS int)";

using (SqlCommand cmd = connection.CreateCommand()) {
cmd.CommandText = queryString;
cmd.Parameters.AddWithValue("@Hoten", "ABC");
cmd.Parameters.AddWithValue("@Sodienthoai", 123456);
var id = cmd.ExecuteScalar();
Console.WriteLine($"ID dữ liệu: {id}");

}

connection.Close();


}
}
}
33 changes: 33 additions & 0 deletions MSSQL/ADO_02_SqlCommand/insertShipper2.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlCommandExam
{
public partial class Program
{
public static void InsertNewShipperExecuteNonQuery()
{
// Mở kết nối MS SQL Server
string sqlconnectStr = "Data Source=localhost,1433;Initial Catalog=xtlab;User ID=SA;Password=Password123";
SqlConnection connection = new SqlConnection(sqlconnectStr);
connection.Open();

// Câu truy vấn gồm: chèn dữ liệu vào và lấy định danh(Primary key) mới chèn vào
string queryString = @"INSERT INTO Shippers (Hoten, Sodienthoai) VALUES (@Hoten, @Sodienthoai)";

using (SqlCommand cmd = connection.CreateCommand()) {
cmd.CommandText = queryString;
cmd.Parameters.AddWithValue("@Hoten", "XYZ");
cmd.Parameters.AddWithValue("@Sodienthoai", 223344);
var rows = cmd.ExecuteNonQuery();
Console.WriteLine($"Số dòng ảnh hưởng: {rows}");

}

connection.Close();


}
}
}
37 changes: 37 additions & 0 deletions MSSQL/ADO_02_SqlCommand/readCate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlCommandExam
{
public partial class Program
{
public static void ReadCategory()
{
string sqlconnectStr = "Data Source=localhost,1433;Initial Catalog=xtlab;User ID=SA;Password=Password123";
SqlConnection connection = new SqlConnection(sqlconnectStr);
connection.Open();

using (SqlCommand command = new SqlCommand("SELECT DanhmucID, TenDanhMuc FROM Danhmuc;", connection))
using (SqlDataReader reader = command.ExecuteReader())
{
// Kiểm tra có kết quả trả về
if (reader.HasRows)
{
// Đọc từng dòng kết quả cho đế hết
while (reader.Read())
{
// Mỗi lần thực hiện read.Read() con trỏ sẽ dịch chuyển đến dòng dữ liệu tiếp
// theo nếu có.
// Đọc dòng dữ liệu dòng hiện tại dùng ký hiệu [chỉ-số-cột] hoặc các hàmg lấy dữ liệu
// từng cột như reader.GetInt21(chỉ-số-cột)
Console.WriteLine("{0}\t{1}", reader[0].ToString(), reader.GetString(1));
}
}
else Console.WriteLine("No rows found.");
}

connection.Close();
}
}
}

0 comments on commit 6f779cb

Please sign in to comment.