I have a simple app which is checking occurrences of values. If there is already occurrences which I am looking for, it display that. If not, it adds.
create table Strings
(
StringID INT IDENTITY(1,1) NOT NULL PRIMARY KEY
, StringValue VARCHAR(100) NOT NULL
)
create table Links
(
LinkID INT IDENTITY(1,1) NOT NULL PRIMARY KEY
,Link VARCHAR(255) NOT NULL
)
CREATE TABLE Occurences
(
OccurenceID INT IDENTITY(1,1) NOT NULL PRIMARY KEY
,StringID INT NOT NULL
,LinkID INT NOT NULL
)
Class:
private SqlConnection conn;
public void Open()
{
this.conn = new SqlConnection();
this.conn.ConnectionString = @"Server=PC\SQLEXPRESS;Database=example;User=sa;Pwd=example;";
this.conn.Open();
}
public void Close()
{
this.conn.Close();
}
public string Obtain(string code)
{
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = @"Server=PC\SQLEXPRESS;Database=example;User=sa;Pwd=example;";
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = code;
sqlConnection.Open();
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
sqlDataReader.Read();
string result = sqlDataReader.GetValue(0).ToString();
sqlConnection.Close();
return result;
}
public void Insert(string StringID, string LinkID)
{
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = @"Server=PC\SQLEXPRESS;Database=example;User=sa;Pwd=example;";
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = string.Concat(new string[]
{
"INSERT INTO Occurences VALUES ('",
StringID,
"', '",
LinkID,
"')"
});
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
Button click:
private void button1_Click(object sender, EventArgs e)
{
try
{
sql.Open();
StringID = sql.Obtain("SELECT StringID from dbo.Strings where StringValue='" + textBox1.Text + "'");
LinkID = sql.Obtain("SELECT LinkID from dbo.Links where Link='" + textBox2.Text + "'");
Occurence = sql.Obtain("SELECT OccurenceID from dbo.Occurences where StringID='" + StringID + "' and LinkID = '" + LinkID + "'");
if (Convert.ToInt32(Occurence) > 0)
{
MessageBox.Show(Occurence);
}
}
catch
{
sql.Insert(StringID, LinkID);
}
finally
{
sql.Close();
}
}
Is this coded well? Should I change my catch to more specific? Should I do something like these?
- If there is no
StringValueindbo.Stringsthen insertStringValue - If there is no
Linkindbo.Linksthen insertLink