Today, I need to make an SMS form to get data from the local server and send messages to clients using a mobile company API. I decided to share my knowledge.
Let's start!
Step 1. In order to make a working form with Oracle database we need the following three classes.
- OracleConnection
- OracleCommand
- OracleDataReader
I just created three objects for all three classes: con for OracleConnection cmd for OracleCommand and DataReader for OracleDataReader. I initialized the first two classes using new but did not initialize the third one as you can see in the attached code.
Now you may see a red squiggling line below the classes which means you did not include the reference of System.Data.OracleClient.dll. In my case, I found it here.
C:\Windows\Microsoft.NET\Framework\v2.0.50727
Step 2. Now you need to tell object con about the connection string and the connection. The following code shows when the form will open, it will connect with the database and then will open the connection.
public Form1()
{
InitializeComponent();
con.ConnectionString = "User Id=id;password=db_pass;Data Source=db_name;";
con.Open();
}
Step 3. And now you are good to go with database commands, I have written a separate function for this.
public void OracleQuery()
{
string sql = "select * from MESSSAGES where STATUS='Pending' order by ID ASC";
orcmd.Connection = con;
orcmd.CommandText = sql;
getListItems();
}
As you can see we are providing knowledge to or cmd about the connection and then the command to work after this there is a function and its definition is here,
private void getListItems()
{
datareader = orcmd.ExecuteReader();
string acnt_status = "Pending";
while (datareader.Read())
{
var status = datareader[4];
if (status.Equals(acnt_status))
{
var contact_no = datareader[1];
var contactLength = contact_no.ToString().Length;
if (contactLength < 12)
{
listView1.LabelWrap = false;
listView1.Items.Add("The Contact Number is wrong " + contact_no);
break;
}
listBox1.Items.Add(datareader[0] + " " + contact_no + " " + status + " " + contactLength);
}
else if (!status.Equals(acnt_status))
{
MessageBox.Show("No pending field found");
break;
}
}
return;
}
In the function above as you can see datareader initialized with orcmd.ExecuteReader(), so simple as the name tells its definitions, we are going to read columns from the database. Columns in the database are indexed from Zero (0). If you want to go to the first column just write datareader[0] and access the ID column. All the data from the database is shown in the list box. And there is an if that if there is any number less than 12 it will thrown out in listview.
Step 4. I explained my code and now you can make the necessary changes as per your requirements.
Learn code and share it.
Your suggestions and comments will be highly appreciated and helpful to me and the readers.