There is a code (it is working), but I would like to know, can I simplify it somehow? Especially interested, can I somehow reduce the number of lines? Simply because of using using , exception blocks, etc., the code is stretched, readability is lost.
Please answer as clearly as possible for a newbie :)
public partial class CreateAds : Form { public MainForm otherForm; string pathBase = Path.Combine(Application.StartupPath, "ads.db"); public CreateAds(MainForm form1) { InitializeComponent(); otherForm = form1; btCreate.Click += (sender, e) => { if (!File.Exists(pathBase)) { SQLiteConnection.CreateFile(pathBase); using (SQLiteConnection con = new SQLiteConnection(string.Format("Data Source={0};", pathBase))) { using (SQLiteCommand cmd = new SQLiteCommand("CREATE TABLE `base` (ID integer primary key, Name varchar, DateCreate varchar, DateEnd varchar, Mesto tinyint(5));", con)) { try { con.Open(); cmd.ExecuteNonQuery(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { con.Close(); } } } } using (SQLiteConnection con = new SQLiteConnection(string.Format("Data Source={0};", pathBase))) { try { con.Open(); string query = string.Format("INSERT INTO 'base' ('Name', 'DateCreate', 'DateEnd', 'Mesto') VALUES ('{0}', '{1}', '{2}', '{3}');", tbName.Text, tbDateCreate.Text, tbDateEnd.Text, tbMesto.Value); using (SQLiteCommand cmd = new SQLiteCommand(query, con)) { cmd.ExecuteNonQuery(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { con.Close(); } } otherForm.dgv.Rows.Add(tbName.Text, tbDateCreate.Text, tbDateEnd.Text, tbMesto.Value, "Удалить"); }; } } public static async Task InsertBase(string Names, string DateCreates, string DateEnds, decimal Mestos) { string pathBase = Path.Combine(Application.StartupPath, "ads.db"); using (SQLiteConnection con = new SQLiteConnection(string.Format("Data Source={0};", pathBase))) { await con.OpenAsync(); string query = string.Format("INSERT INTO 'base' ('Name', 'DateCreate', 'DateEnd', 'Mesto') VALUES ('{0}', '{1}', '{2}', '{3}');", Names, DateCreates, DateEnds, Mestos); using (SQLiteCommand cmd = new SQLiteCommand(query, con)) { await cmd.ExecuteNonQueryAsync(); } } }
usingassumes that you do not need to prescribeClose, because class implementsIDisposable- Bulson