57. Ma'lumotlar oqimi yordamida SQLite ma'lumotlar bazasidan ma'lumotlarni o'qiydigan va uni formatlangan tarzda ko'rsatadigan C# dasturini yozing.
Javob:
using System.Data.SQLite;
// Ma'lumotlar bazasiga ulanish
SQLiteConnection connection = new SQLiteConnection("Data Source=myDatabase.db;Version=3;");
connection.Open();
// SQL so'rovni tuzish va bajargan natijani qaytarish
string sql = "SELECT * FROM MyTable";
SQLiteCommand command = new SQLiteCommand(sql, connection);
SQLiteDataReader reader = command.ExecuteReader();
// Natijalarni ko'rib chiqish
while (reader.Read())
{
int id = reader.GetInt32(0);
string name = reader.GetString(1);
DateTime date = reader.GetDateTime(2);
Console.WriteLine($"ID: {id}, Name: {name}, Date: {date}");
}
// Ma'lumotlar bazasiga aloqani yopish
reader.Close();
command.Dispose();
connection.Close();
58. Ma'lumotlar oqimi yordamida MySQL ma'lumotlar bazasiga ma'lumotlarni yozadigan C# dasturini amalga oshiring.
Javob:
using System;
using System.Data;
using System.IO;
using MySql.Data.MySqlClient;
class Program
{
static void Main(string[] args)
{
string connectionString = "server=localhost;port=3306;database=mydatabase;uid=myusername;password=mypassword";
string query = "INSERT INTO mytable (name, age) VALUES (@name, @age)";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
// Create a data stream from a CSV file
string csvFilePath = "data.csv";
using (StreamReader reader = new StreamReader(csvFilePath))
{
// Read the header line
string[] headers = reader.ReadLine().Split(',');
// Prepare the command
using (MySqlCommand command = new MySqlCommand(query, connection))
{
// Use parameters to prevent SQL injection
command.Parameters.Add("@name", MySqlDbType.VarChar);
command.Parameters.Add("@age", MySqlDbType.Int32);
// Read the data lines and insert them into the database
while (!reader.EndOfStream)
{
string[] fields = reader.ReadLine().Split(',');
command.Parameters["@name"].Value = fields[0];
command.Parameters["@age"].Value = int.Parse(fields[1]);
command.ExecuteNonQuery();
}
}
}
connection.Close();
}
Console.WriteLine("Data inserted successfully.");
}
}
Ushbu kod CSV faylini o'qiydi va ma'lumotlar oqimi yordamida uning ma'lumotlarini (nomi va yoshi) MySQL ma'lumotlar bazasiga kiritadi. Ushbu koddan foydalanish uchun ulanish qatorini oʻzingizga almashtirishingiz va CSV fayli toʻgʻri formatga ega ekanligiga ishonch hosil qilishingiz kerak (bir sarlavha qatoridan soʻng bir yoki bir nechta maʼlumotlar qatori, har birida vergul bilan ajratilgan nom va yosh maydonlari mavjud).
Do'stlaringiz bilan baham: |