Can't insert the record to database C# SQLite - c#

I've been struggling with an error related to the database. Basically I have an SQLite db and I want to insert the data, but after I execute the method, no data is written to the db but no errors are shown either. This is my code:
The db connection class:
class SqlDb
{
public static SQLiteConnection SqLiteConnection;
public static string DATABASE_WAREHOUSE = "DaneDB.db";
public static string DATABASE_LACZKA =
$"Data Source= {DATABASE_WAREHOUSE};Version=3;New=False;Compress=True;";
public SQLiteConnection Connect()
{
try
{
SqLiteConnection = new SQLiteConnection(DATABASE_LACZKA);
SqLiteConnection.Open();
}
catch (Exception e)
{
MessageBox.Show($"Could not connect to the database {e}");
throw;
}
return SqLiteConnection;
}
public void Disconnect()
{
SqLiteConnection.Close();
}
}
and the inserting method
private void LoadToDb_Click(object sender, EventArgs e)
{
Data modelData = new Data();
SqlDb db = new SqlDb();
SQLiteConnection sqLiteConnection = db.Connect();
SQLiteCommand sqLiteCommand = sqLiteConnection.CreateCommand();
try
{
modelData.Name = firstName.Text;
modelData.Age = Convert.ToInt32(DisplayAge.Text);
modelData.LastName = LastName.Text;
sqLiteCommand.CommandText =
$"insert into DANE values('{modelData.Name}', '{modelData.LastName}', '{modelData.Age}')";
db.Disconnect();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
I also have the options of database set to:
Build Action: Content
Copy to output directory: Copy always

You forgot to execute this command:
sqLiteCommand.ExecuteNonQuery();
Please refer to documentation: ExecuteNonQuery

Related

How put connection in report runtime

I would like send connection for report in DevExpress, and send query for this report I call report with code bellow:
private void Form14_Load(object sender, EventArgs e)
{
try {
XtraReport report = XtraReport.FromFile(#"C:\\a\\Report2.repx", true);
ReportPrintTool printTool = new ReportPrintTool(report);
printTool.ShowPreviewDialog();
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
}
In the general case, your report is connected to data via the SqlDataSource component. So, I suggest you update the connection at the SqlDataSource instance level. For that purpose, just get the existing data source from your XtraReport class:
var sqlDataSource = xtraReport.DataSource as SqlDataSource;
sqlDataSource.ConnectionParameters = ...;
Please refer to the Specify data connection article to learn how to change the data source's connection parameters.
You can create your own report implementation where you can update the connection string by checking the connection strings used in the reports and the sub reports.
In below example, a Typed Dataset is used to create the reports and then you can update the connection string of the table adapters on the initialization.
Refere this below implementation:
// Base Report
public partial class BaseReport: DevExpress.XtraReports.UI.XtraReport, IDisposable
{
public List<SQLiteConnection> GetConnectionList
{
get { return connectionList; }
}
public List<SimergyBaseReport> GetSubReportList
{
get { return subReportList; }
}
protected List<SQLiteConnection> connectionList = new List<SQLiteConnection>();
protected List<SimergyBaseReport> subReportList = new List<SimergyBaseReport>();
public void UpdateConnectionString(String connectionString)
{
#if !RPT_DESIGN
connectionString = GlobalUtilities.GetOutputConnectionString(connectionString);
foreach (SQLiteConnection conn in connectionList)
{
conn.Close();
conn.ConnectionString = connectionString;
reportDataSet.Clear();
}
foreach (BaseReport subReport in comparisonSubReportList)
{
if (subReport != null)
subReport.UpdateConnectionString(connectionString);
}
#endif
}
}
// Report
public partial class UsageSummary : Simergy.Reporting.Reports.BaseReport
{
public ClimaticSummary()
{
InitializeComponent();
}
public ClimaticSummary(String connectionString, Model model)
: base(model)
{
InitializeComponent();
connectionList.Add(applicationUsageTableAdapter.Connection);
connectionList.Add(dailyUsage_SUMMARYTableAdapter.Connection);
subReportList.Add(xrSubreport1.ReportSource as BaseReport);
subReportList.Add(xrSubreport2.ReportSource as BaseReport);
subReportList.Add(footerSubReport.ReportSource as BaseReport);
reportDataSet = report_DataSet1;
UpdateConnectionString(connectionString);
}
}
// Custom print control to render the reports
public partial class ReportViewControl : PrintControl
{
private SimergyBaseReport CurrentReport = null;
public ReportViewControl()
{
InitializeComponent();
}
public void SetReport(SimergyBaseReport report)
{
CurrentReport = report;
if (CurrentReport != null)
{
this.PrintingSystem = report.PrintingSystem;
SetupButtonVisability();
report.CreateDocument();
report.RecreateDocumentMap();
this.PrintingSystem = report.PrintingSystem;
}
}
public void RefreshReport()
{
this.PrintingSystem = null;
this.PrintingSystem = CurrentReport.PrintingSystem;
CurrentReport.CreateDocument(true);
}
}
///Usage
BaseReport report = new UsageSummary(someConnectionString);
ReportViewControl viewer = new ReportViewControl();
viewer.SetReport(report);
form1.Controls.Add(viewer);

Connection to sql database from visual studio

I'm trying to connect to a database, I also have a bool function to check if the connection worked. I searched all over the internet but can't really find how to do it properly.
public class DBConnection : DBLabsDLL.DBConnectionBase
{
///*
// * The constructor
// */
public DBConnection()
{
string connectionString = null;
SqlConnection connection;
connectionString = "Data Source=SQL Server;Initial Catalog=www3.idt.mdh.se;User ID=ezi15001;Password=********";
connection = new SqlConnection(connectionString);
}
public override bool login(string username, string password)
{
try
{
using (var connection = new SqlConnection(connectionString)
{
connection.Open();
return true;
}
catch (SqlException)
{
return false;
}
}

How to check for database availability

I have the following code to test DB connection, it runs periodically to test for DB availability:
private bool CheckDbConn()
{
SqlConnection conn = null;
bool result = true;
try
{
conn = DBConnection.getNewCon();
ConnectionState conState = conn.State;
if (conState == ConnectionState.Closed || conState == ConnectionState.Broken)
{
logger.Warn(LogTopicEnum.Agent, "Connection failed in DB connection test on CheckDBConnection");
return false;
}
}
catch (Exception ex)
{
logger.Warn(LogTopicEnum.Agent, "Error in DB connection test on CheckDBConnection", ex);
return false; // any error is considered as db connection error for now
}
finally
{
try
{
if (conn != null)
{
conn.Close();
}
}
catch (Exception ex)
{
logger.Warn(LogTopicEnum.Agent, "Error closing connection on CheckDBConnection", ex);
result = false;
}
}
return result;
}
And:
static public SqlConnection getNewCon()
{
SqlConnection newCon = new SqlConnection();
newCon.ConnectionString = DBConnection.ConnectionString; // m_con.ConnectionString;
newCon.Open();
return newCon;
}
My question is: will this work as expected?
Specifically, I'm concerned about the test of the ConnectionState. Is it possible that the state will be: connecting (since Open() is synchronous)?
What should I do in that case?
You can try like this.
public bool IsServerConnected()
{
using (var l_oConnection = new SqlConnection(DBConnection.ConnectionString))
{
try
{
l_oConnection.Open();
return true;
}
catch (SqlException)
{
return false;
}
}
}
SqlConnection will throw a SqlException when it cannot connect to the server.
public static class SqlExtensions
{
public static bool IsAvailable(this SqlConnection connection)
{
try
{
connection.Open();
connection.Close();
}
catch(SqlException)
{
return false;
}
return true;
}
}
Usage:
using(SqlConnection connection = GetConnection())
{
if(connection.IsAvailable())
{
// Success
}
}
Your code seems fine, but you really need to use the IDisposable pattern, and some naming convention too:
private bool CheckDbConnection(string connectionString)
{
try
{
using(var connection = new SqlConnection(connectionString))
{
connection.Open();
return true;
}
}
catch (Exception ex)
{
logger.Warn(LogTopicEnum.Agent, "Error in DB connection test on CheckDBConnection", ex);
return false; // any error is considered as db connection error for now
}
}
And connection.Close() is not supposed to throw. Just use the using block and your are fine.
No need to test the Close state, since you have just opened it.
More about the Broken state:
Broken The connection to the data source is broken. This can occur
only after the connection has been opened. A connection in this state
may be closed and then re-opened. (This value is reserved for future
versions of the product.)
So really, no need to test that.
The Connecting state could be catch if you are in a multithread context and your instance of connection is shared. But it is not your case here.
This code does not block a UI if called.
public static class DatabaseExtensions
{
public static async Task<bool> IsConnectionViable(this string connectionStr)
{
await using var sqlConn = new SqlConnection(connectionStr);
return await sqlConn.IsConnectionViable();
}
public static async Task<bool> IsConnectionViable(this SqlConnection connection)
{
var isConnected = false;
try
{
await connection.OpenAsync();
isConnected = (connection.State == ConnectionState.Open);
}
catch (Exception)
{
// ignored
}
return isConnected;
}
}
actually, in visual studio, connection class has sonnectionstate property.
when connection state changes, connections statechange event is been trigerred.
you might want to check this article.
https://msdn.microsoft.com/en-us/library/aa326268(v=vs.71).aspx
I was using #Ramesh Durai's solution but found that on my setup at least (the app calling/testing periodically after the app had started; using .Net 3.5 with Sql Server 2012 database) that the first call to IsConnected() after taking the database offline was returning true. However, it was throwing the expected exception on the ExecuteScalar() line below:
public bool IsConnected() {
using (var conn = new SqlConnection(DBConnection.ConnectionString)) {
using (var cmd = New SqlCommand("SELECT 1", conn)) {
try {
conn.Open();
cmd.ExecuteScalar();
return true;
} catch (SqlException) {
return false;
}
}
}
}
This code is for Mysql.
public class Program
{
string connection = "SERVER=localhost; user id=root; password=; database=dbname";
private void Form1_Load(object sender, System.EventArgs e)
{
checkifconnected();
}
private void checkifconnected()
{
MySqlConnection connect = new MySqlConnection(connection);
try{
connect.Open();
MessageBox.Show("Database connected");
}
catch
{
MessageBox.Show("you are not connected to database");
}
}
public static void Main()
{
}
}

Cannot implicitly convert type 'void' to 'string'

I've tried for a while now and I really dont get it. I recive error "Cannot implicitly convert type 'void' to 'string'"
I have tried multiple variants of string, int, nothing, void, public, static and nope I really dont get it right.
I want to get one value from my db thoug my DAL and BLL, my code looks like this.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Repeater1.DataSource = BLL.getGames();
Repeater1.DataBind();
var culture = CultureInfo.GetCultureInfo("sv-SE");
var dateTimeInfo = DateTimeFormatInfo.GetInstance(culture);
var dateTime = DateTime.Today;
int weekNumber = culture.Calendar.GetWeekOfYear(dateTime, dateTimeInfo.CalendarWeekRule, dateTimeInfo.FirstDayOfWeek);
string mroundY = dateTime.Year.ToString();
string mroundW = weekNumber.ToString();
string mrounddate = mroundY + mroundW;
string mround = BLL.getMroundGames(mrounddate); <-- Here's the error
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
}
}
My BLL looks like this;
public class BLL
{
public static void getMroundGames(string mrounddate)
{
SqlCommand getMroundGames = new SqlCommand("SELECT mround FROM gameTB where mround = #mrounddate");
DAL.ExecuteNonQuery(getMroundGames);
}
}
Also tried this;
public class BLL
{
public static DataTable getMroundGames(string mrounddate)
{
SqlCommand getMroundGames = new SqlCommand("SELECT mround FROM gameTB where mround = #mrounddate");
getMroundGames.Parameters.Add("#mrounddate", SqlDbType.VarChar, 10).Value = mrounddate;
return DAL.GetData(getMroundGames);
}
}
And finaly my DAL looks like this;
public class DAL
{
public static SqlConnection GetConnection()
{
SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["tiptopConnectionString"].ConnectionString);
conn.Open();
return conn;
}
public static DataTable GetData(SqlCommand command)
{
try
{
using (SqlConnection conn = GetConnection())
{
using (DataSet ds = new DataSet())
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = command;
da.SelectCommand.Connection = conn;
da.Fill(ds);
return ds.Tables[0];
}
}
}
}
catch (Exception err)
{
throw new ApplicationException(string.Format("Felmeddelande:{0}", err.Message));
}
}
public static object ExecuteScalar(SqlCommand command)
{
using (SqlConnection conn = GetConnection())
{
command.Connection = conn;
object result = command.ExecuteScalar();
return result;
}
}
public static void ExecuteNonQuery(SqlCommand command)
{
using (SqlConnection conn = GetConnection())
{
command.Connection = conn;
command.ExecuteNonQuery();
}
}
}
Where to begin?
The signature for this is wrong;
public static void getMroundGames(string mrounddate)
You need to change it to something similar to ;
public static string getMroundGames(string mrounddate)
Retrieve the string value from your DAL and return to the consumer accordingly.
var dt = Dal.GetData();
return (string)dt.Rows[0]["field"];
However, in all honesty, I would not be passing a datatable from your DAL to your BLL. I would return the string directly or introduce a DTO and populate this from your DAL through your BLL, back to the consumer.
You need to add a return type of string to getMroundGameas(string mrounddate).
It's not clear what type of object DAL is, but you should also probably use ExecuteReader method, http://msdn.microsoft.com/en-us/library/bb344397.aspx
rather then ExecuteNonQuery. This will return a Reader which can be queried for the value returned by the select statement.
Finally you should return the value.

Global ConnectionString not being initialized

I have my connection string stored in a myGlobals.cs page as below:
/* Connection String */
public static string conString
{
get { return _conString; }
set { _conString = ConfigurationManager.ConnectionStrings["BaseConnectionString"].ToString(); }
}
I have my code setup in the 4 tier architecture. So I have a Business Object folder, Business Access Layer & Data Access Layer. If I move the connection string into the DAL structure it works fine. Other wise I get this error:
The ConnectionString property has not been initialized
Is the myGlobals.cs class not being included before all this or does it need to be changed around?
Here is my Data Access Layer:
public DataTable Load()
{
SqlConnection conn = new SqlConnection(MyGlobals.conString);
SqlDataAdapter dAd = new SqlDataAdapter("administratorGetAll", conn);
dAd.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet dSet = new DataSet();
try
{
dAd.Fill(dSet, "AdministratorsTable");
return dSet.Tables["AdministratorsTable"];
}
catch
{
throw;
}
finally
{
dSet.Dispose();
dAd.Dispose();
conn.Close();
conn.Dispose();
}
}
The property 'setter' doesn't get called automatically; its code is executed when you put the property on the left-hand side of an assignment - MyClass.MyProperty = "new value";
You want to be doing this:
public static string conString
{
get { return ConfigurationManager.ConnectionStrings["BaseConnectionString"]; }
}

Categories

Resources