47. Ma'lumotlar bazasiga ma'lumotlarni yozish uchun ma'lumotlar oqimidan
foydalanadigan C# dasturini yarating.
Javob:
using System;
using System.Data.SqlClient;
namespace DataWriter
{
class Program
{
static void Main(string[] args)
{
// Create the connection string
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword";
// Create the SQL command to insert data
string insertQuery = "INSERT INTO myTable (column1, column2, column3) VALUES (@val1, @val2, @val3)";
// Create the connection and command objects
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(insertQuery, connection))
{
// Set the parameter values
command.Parameters.AddWithValue("@val1", "Value 1");
command.Parameters.AddWithValue("@val2", "Value 2");
command.Parameters.AddWithValue("@val3", "Value 3");
// Open the connection and execute the command
connection.Open();
command.ExecuteNonQuery();
}
}
}
}
48. Ma'lumotlar bazasidan ma'lumotlarni o'qish va uni ko'rsatish uchun ma'lumotlar oqimidan foydalanadigan C# dasturini amalga oshiring.
Javob:
Ma'lumotlar bazasidan ma'lumotlarni o'qish va ularni C# yordamida ko'rsatish uchun:
using System;
using System.Data;
using System.Data.SqlClient;
class Program {
static void Main(string[] args) {
string connectionString = "your_connection_string_here";
SqlConnection connection = new SqlConnection(connectionString);
try {
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM your_table_name_here", connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
Console.WriteLine("{0}\t{1}", reader.GetString(0), reader.GetString(1));
}
reader.Close();
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
finally {
connection.Close();
}
}
}
Do'stlaringiz bilan baham: |