Код: Выделить всё
namespace Material
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
List users = new List();
Database data = new Database();
List names = Database.GetFromDB();
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = names;
label1.Text = names[0].name.ToString();
}
}
}
Код: Выделить всё
namespace Material
{
public class User
{
public int id;
public string name;
public string email;
public User(int id, string name, string email)
{
this.id = id;
this.name = name;
this.email = email;
}
public void PrintUser()
{
Console.WriteLine(id + " " + name + " " + email);
}
}
}
Код: Выделить всё
namespace Material
{
public class Database
{
public static string dbPath = "Data Source= C:\\Users\\Jonathan\\Documents\\csharp\\Material\\Material\\bids.db"; // Path to your database file
public static void MakeDB()
{
SQLiteConnection connection = new SQLiteConnection(dbPath);
connection.Open(); // This will create the database file if it doesn't exist
string createTableSql = @"CREATE TABLE IF NOT EXISTS Users2 (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT NOT NULL,
Email TEXT UNIQUE
);";
SQLiteCommand command = new SQLiteCommand(createTableSql, connection);
command.ExecuteNonQuery();
}
public static void AddtoDB(string name)
{
SQLiteConnection connection = new SQLiteConnection(dbPath);
connection.Open(); // This will create the database file if it doesn't exist
string createTableSql = "INSERT INTO Users (Id, Name, Email) VALUES (Null, @Name, @Email)";
SQLiteCommand command = new SQLiteCommand(createTableSql, connection);
command.Parameters.AddWithValue("@Name", name);
command.Parameters.AddWithValue("@Email", name + "@gmail.com");
command.ExecuteNonQuery();
}
public static List GetFromDB()
{
SQLiteConnection connection = new SQLiteConnection(dbPath);
connection.Open();
var sql = "SELECT * FROM Users";
using var command = new SQLiteCommand(sql, connection);
using var reader = command.ExecuteReader();
List myObjectList = [];
if (reader.HasRows)
{
while (reader.Read())
{
var id = reader.GetInt32(0);
var name = reader.GetString(1);
var email = reader.GetString(2);
myObjectList.Add(new User(id, name, email));
}
}
else
{
Console.WriteLine("No authors found.");
}
return myObjectList;
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... st-c-sharp
Мобильная версия