using System.Data.SqlClient;
My demo will read ini file with key and value same
[DataBase]
ServerName=VILH-PC\SQLEXPRESS
DBName=ManageCustomers
Login=sa
Key=123
This demo using some lib function
WriteLog
public static void WriteLog(string strLogFileName, System.Exception ex)
{
try
{
string strDate = "[" +
DateTime.Today.Year + "-" + DateTime.Today.Month +
"-" + DateTime.Today.Day + " " +
DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":"
+ DateTime.Now.Second +
"]: ";
string strLogMessage = " * " + strDate + "Message = "
+ ex.Message.ToString() + "; TargetSite = " + ex.TargetSite +
"; StackTrace = " + ex.StackTrace;
WriteFile(strLogFileName, strLogMessage, 2, Encoding.UTF8);
}
catch { }
}
Explore My Other Channel for More Cool and Valuable Insights
👉 Youtube Learn Tech Tips👉 Tiktok
👉 Facebook:WriteFile
/// <summary>
/// Ghi Noi Dung strContent vao duong dan strPath
/// \nMode=1: CreateNew (co se ghi de, chua co tao moi) / 2:Append
/// </summary>
/// <param name="strPath" /> Duong Dan file
/// <param name="strContent" /> Noi Dung file
/// <param name="Mode" /> 1: CreateNew (co se ghi de, chua co tao moi) / 2:Append
/// <returns> true -> succeed </returns>
static public bool WriteFile(string szPath, string szContent, int iMode, Encoding en) {
bool bFlag = false;
FileStream fs = null;
try
{
switch (iMode)
{
case 1:
fs = new FileStream(szPath, FileMode.Create);
break;
case 2:
fs = new FileStream(szPath, FileMode.Append);
break;
default:
fs = new FileStream(szPath, FileMode.Append);
break;
}
using (StreamWriter sw = new StreamWriter(fs, en))
{
sw.WriteLine(szContent);
sw.Close();
}
fs.Close();
bFlag = true;
}
catch
{
return bFlag;
}
return bFlag;
}
Read Ini File
you can view here
Full source code
/* ---------------------------------------------------
* Author: ViLH / Zidane (huuvi168@gmail.com)
* Email: huuvi168@gmail.com
* Last Modified: 03-01-2015
* ---------------------------------------------------
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace ManageCustomers
{
public class clsConnectDB
{
public static string _connectionString;
//protected OleDbConnection _connection = null;
private SqlConnection _connection = null;
//protected OleDbDataAdapter _adapter;
private SqlDataAdapter _adapter;
//protected OleDbCommand _command;
private SqlCommand _command;
public clsConnectDB()
{
var iniFile = new clsIniFile(frmMain.APP_CONFIG);
// server Name: VILH-PC\SQLEXPRESS
var szServerName = iniFile.Read("ServerName", "DataBase");
// DataBase Name: ManageCustomers
var szDBName = iniFile.Read("DBName", "DataBase");
// user name: sa
var szLogin = iniFile.Read("Login", "DataBase");
// password: 123
var szPassWord = iniFile.Read("Key", "DataBase");
_connectionString = "Data Source=" + szServerName +
";Initial Catalog=" + szDBName + " ;User Id=" +
szLogin + ";Password=" + szPassWord;
connect();
}
public SqlCommand Command
{
get { return _command; }
set { _command = value; }
}
public SqlDataAdapter Adapter
{
get { return _adapter; }
set { _adapter = value; }
}
public SqlConnection Connection
{
get { return _connection; }
set { _connection = value; }
}
public static string ConnectionString
{
get
{
return _connectionString;
}
set
{
_connectionString = value;
}
}
public void connect()
{
try
{
_connection = new SqlConnection(_connectionString);
_connection.Open();
}
catch (System.Exception ex)
{
clsCommon.WriteLog(clsCommon.getLogDailyFileName(), ex);
throw new Exception(ex.Message);
}
}
public void disconnect()
{
if (_connection != null)
_connection.Close();
}
public ArrayList executeQuery()
{
ArrayList arr = null;
try
{
connect();
_command.Connection = _connection;
_adapter = new SqlDataAdapter(_command);
DataSet dataset = new DataSet();
_adapter.Fill(dataset);
arr = ConvertDataSetToArrayList(dataset);
}
catch (Exception ex)
{
clsCommon.WriteLog(clsCommon.getLogDailyFileName(), ex);
throw new Exception(ex.Message);
}
finally
{
disconnect();
}
return arr;
}
public int executeNonQuery()
{
int affectedRow = -1;
try
{
connect();
_command.Connection = _connection;
affectedRow = _command.ExecuteNonQuery();
}
catch (Exception ex)
{
clsCommon.WriteLog(clsCommon.getLogDailyFileName(), ex);
throw new Exception(ex.Message);
}
finally
{
disconnect();
}
return affectedRow;
}
protected ArrayList ConvertDataSetToArrayList(DataSet dataset)
{
ArrayList arr = new ArrayList();
DataTable dt = dataset.Tables[0];
int i, n = dt.Rows.Count;
for (i = 0; i < n; i++)
{
object obj = GetDataFromDataRow(dt, i);
arr.Add(obj);
}
return arr;
}
protected virtual object GetDataFromDataRow(DataTable dt, int i)
{
return null;
}
public IDataReader executeQuery(string sqlString)
{
_command = new SqlCommand(sqlString, _connection);
return _command.ExecuteReader();
}
// update, delete
public void executeNonQuery(string sqlString)
{
try
{
_command = new SqlCommand(sqlString, _connection);
_command.ExecuteNonQuery();
}
catch (System.Exception ex)
{
clsCommon.WriteLog(clsCommon.getLogDailyFileName(), ex);
throw new Exception(ex.Message.ToString());
}
finally
{
disconnect();
}
}
public object executeScalar(string sqlString)
{
try {
_command = new SqlCommand(sqlString, _connection);
return _command.ExecuteScalar();
}
catch (System.Exception ex)
{
clsCommon.WriteLog(clsCommon.getLogDailyFileName(), ex);
throw new Exception(ex.Message.ToString());
}
finally
{
disconnect();
}
}
/// <summary>
/// Execute Query to Dataset with sqlstring
/// </summary>
public DataSet ExecuteQueryToDataSet(string dbString)
{
DataSet ds = new DataSet();
try
{
connect();
SqlDataAdapter adapter = new SqlDataAdapter(dbString, _connection);
adapter.Fill(ds);
}
catch (System.Exception ex)
{
clsCommon.WriteLog(clsCommon.getLogDailyFileName(), ex);
throw new Exception(ex.Message.ToString());
}
finally
{
disconnect();
}
return ds;
}
public DataTable ExecuteQueryToDataTable(string dbString)
{
return ExecuteQueryToDataSet(dbString).Tables[0];
}
}
}
If you have any feedback in Connect SQL Server using C#. Please leave your comment, we can discuss about it!
Are you interested in topic How to connect database SQL Server Using C# from Webzone Tech Tips? If you have any thoughts or questions, please share them in the comment section below. I would love to hear from you and chat about it
Webzone tech tips Zidane