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