I am using the following code to consume a CUBRID database java stored procedure.
string ConnectionString = "server=localhost;database=demodb;port=30000;user=dba;password=123456";
DataTable dt = new DataTable();
DataSet ds = new DataSet();
CUBRIDConnection con = new CUBRIDConnection(ConnectionString);
CUBRIDCommand com = new CUBRIDCommand();
com.CommandType = CommandType.StoredProcedure;
com.Connection = con;
com.CommandText = "select rset()";
CUBRIDParameter pan = new CUBRIDParameter();
pan.Direction = ParameterDirection.Output;
pan.CUBRIDDataType = CUBRIDDataType.CCI_U_TYPE_RESULTSET;
pan.ParameterName = "?p1";
CUBRIDDataAdapter dap = new CUBRIDDataAdapter(com);
con.Open();
int val = dap.Fill(ds);
con.Close();
and in the server use the next function and stored procedure in the server
public class JavaSP3 {
public static ResultSet TResultSet(){
try {
Class.forName("cubrid.jdbc.driver.CUBRIDDriver");
Connection con = DriverManager.getConnection("jdbc:default:connection:");
String sql = "select * from athlete";
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
((CUBRIDResultSet)rs).setReturnable();
return rs;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
and the function code is this
CREATE FUNCTION "rset"() RETURN CURSOR
AS LANGUAGE JAVA
NAME 'JavaSP3.TResultSet() return cubrid.jdbc.driver.CUBRIDResultSet'
I run this with a function that result a string and return the value, but when I change to CUBRIDResultSet value dont work and CUBRID says>
execute error:-911
line 1 is not executed (error)
Error description:
Invalid call: it can not return ResultSet.
Please, I have 3 days trying to solve this any one can help me?
ADO.NET dont provide support for ResultSet.
http://www.cubrid.org/?mid=forum&category=195532&document_srl=358924
using System.Data;
using CUBRID.Data.CUBRIDClient;
using System.Data.Common;
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string ConnectionString = "server=localhost;database=demodb;port=30000;user=dba;password=123456";
DataTable dt = new DataTable();
DataSet ds = new DataSet();
CUBRIDConnection con = new CUBRIDConnection(ConnectionString);
CUBRIDCommand com = new CUBRIDCommand();
com.CommandType = CommandType.Text; //Important ADO.NET driver crash using call convention
com.Connection = con;
com.CommandText = "select rset();";
CUBRIDParameter pan = new CUBRIDParameter();
con.Open();
DbDataReader reader = com.ExecuteReader();
CustomAdapter da = new CustomAdapter();
da.FillFromReader(dt, reader);
con.Close();
DataRow fila = dt.Rows[0];
Console.WriteLine(fila[0].ToString());
Console.ReadKey();
}
}
public class CustomAdapter : System.Data.Common.DbDataAdapter
{
public int FillFromReader(DataTable dataTable, IDataReader dataReader)
{
return this.Fill(dataTable, dataReader);
}
protected override System.Data.Common.RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow a, IDbCommand b, StatementType c, System.Data.Common.DataTableMapping d)
{
return (System.Data.Common.RowUpdatedEventArgs)new EventArgs();
}
protected override System.Data.Common.RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow a, IDbCommand b, StatementType c, System.Data.Common.DataTableMapping d)
{
return (System.Data.Common.RowUpdatingEventArgs)new EventArgs();
}
protected override void OnRowUpdated(System.Data.Common.RowUpdatedEventArgs value)
{
}
protected override void OnRowUpdating(System.Data.Common.RowUpdatingEventArgs value)
{
}
}
java class
import java.sql.*;
import cubrid.jdbc.driver.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class JavaSP3 {
public static String TResultSet(){
ResultSet rs = null;
Statement stmt = null;
String sql;
try {
Class.forName("cubrid.jdbc.driver.CUBRIDDriver");
Connection con = DriverManager.getConnection("jdbc:default:connection:");
((CUBRIDConnection)con).setCharset("euc_kr");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder =factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element results = doc.createElement("Results");
doc.appendChild(results);
sql = "select * from athlete";
stmt=con.createStatement();
rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
while (rs.next()) {
Element row = doc.createElement("Row");
results.appendChild(row);
for (int ii = 1; ii <= colCount; ii++) {
String columnName = rsmd.getColumnName(ii);
Object value = rs.getObject(ii);
Element node = doc.createElement(columnName);
node.appendChild(doc.createTextNode(value.toString()));
row.appendChild(node);
}
}
String valor = getDocumentAsXml(doc);
return valor;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static String getDocumentAsXml(Document doc)
throws TransformerConfigurationException, TransformerException {
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
//transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
transformer.setOutputProperty
("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
java.io.StringWriter sw = new java.io.StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
return sw.toString();
}
}
Cubrid function
CREATE FUNCTION "rset"() RETURN STRING
AS LANGUAGE JAVA
NAME 'JavaSP3.TResultSet() return java.lang.String'
This allow you get data from Java stored procedures in CUBRID using ADO.NET
Related
I'm trying at the moment to get an information from a database and want to save it in a string, but yeah not sure about how really to do it right.
This is my code, where I open the LoadSql function:
public void LoadData(string KNR, string WNR, String filter)
{
// WHERE
const string sqlTemplate = "SELECT KUNDENAUFTRAGSNR FROM MESSFELD.AUSSTANDSDATEN WHERE FTNR = '" + txt_Barcode_read.Text + "'";
string sql = string.Format(sqlTemplate, filter);
Database cdb = new Database();
// try to connect and cancel on error
if (!cdb.Open("**********", "*********"))
{
SetStatusText("Datenbank ist nicht verfügbar.");
return;
}
WNR = cdb.LoadSql(sql);
cdb.Close();
}
And here is the LoadSQL function:
public DataTable LoadSql(string sql)
{
try
{
OracleCommand command = new OracleCommand(sql, _con);
command.InitialLONGFetchSize = -1;
OracleDataReader rdr = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
return dt;
}
catch
{
return null;
}
}
For the moment the LoadSQL is saving in datatable, how to change for saving the number in the string WNR?
You can re-write your LoadSQL function to something like this :
public string LoadSql(string sql)
{
try
{
OracleCommand command = new OracleCommand(sql, _con);
command.InitialLONGFetchSize = -1;
OracleDataReader rdr = command.ExecuteReader();
rdr.Read();
if(rdr.HasRows)
return rdr.GetString(0);
else
return "";
}
catch
{
return null;
}
}
I have a class file where I declare readonly string of my query to be used in a method. I met the error of
Must declare the scalar variable "#DBID"
May I know if I declare my variables wrongly?
Below are the code snippets:
Class file:
private static readonly string QUERY_GETMATCHEDRECORD = "SELECT [Title], [ItemLink], [RecordDocID] FROM [ERMS].[dbo].[Records] WHERE [ID] = #DBID AND [V1RecordID] = #recID AND [V1RecordDocID] = #recDocID";
public DataTable GetMatchedRecord(string DBID, string recID, string recDocID)
{
string Method = System.Reflection.MethodBase.GetCurrentMethod().Name;
DataTable dt = new DataTable();
try
{
using (DB db = new DB(_datasource, _initialCatalog))
{
db.OpenConnection();
using (SqlCommand command = new SqlCommand())
{
string commandText = QUERY_GETMATCHEDRECORD .FormatWith(DBID,recID,recDocID);
_log.LogDebug(Method, "Command|{0}".FormatWith(commandText));
command.CommandText = commandText;
dt = db.ExecuteDataTable(command);
}
db.CloseConnection();
}
}
catch (Exception ex)
{
_log.LogError(Method, "Error while retrieving matching records |{0}".FormatWith(ex.Message));
_log.LogError(ex);
}
return dt;
}
Program .cs file:
MatchedRecords = oDB.GetMatchedRecord(DBID, RecID, RecDocID);
using '#'-notated variables will only work if you add the parameters to the commands parameter-collection.
try the following:
using (DB db = new DB(_datasource, _initialCatalog))
{
db.OpenConnection();
using (SqlCommand command = new SqlCommand())
{
command.CommandText = QUERY_GETMATCHEDRECORD;
command.Parameters.AddWithValue("#DBID", DBID);
command.Parameters.AddWithValue("#recID", recID);
command.Parameters.AddWithValue("#recDocID",recDocID);
dt = db.ExecuteDataTable(command);
}
db.CloseConnection();
}
I'm trying to retrieve values from an Oracle database using C# WebMethod, ajax and JavaScript, I have another page with exactly all the same functions and methods (using MSSQL Database) and work fine, but now I want to do it with Oracle. This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Oracle.DataAccess.Client;
using System.Data;
using System.Configuration;
/// <summary>
/// Summary description for OracleConexion
/// </summary>
public class OracleConexion
{
OracleConnection conn;
DataTable dt;
OracleDataAdapter da;
OracleDataReader dr;
DataSet ds;
OracleCommand cmd;
public OracleConexion()
{
conn = new OracleConnection("Data Source = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = ***.**.**.***)(PORT = ****)))(CONNECT_DATA = (SERVER = DEDICATED)(SID = *****))); User Id = *****; Password = ****;");
}
private void Open()
{
string canConnect;
try
{
conn.Open();
canConnect = "Nice";
}
catch (Exception ex)
{
//Code Updated
canConnect = ex.Message.ToString();
}
Console.Write(canConnect);
}
private void Close()
{
try
{
conn.Close();
}
catch (Exception ex)
{
}
}
public DataTable ConsultarTablas(string opcion)
{
dt = new DataTable();
ds = new DataSet();
string sql = "";
switch (opcion)
{
case "Datos":
sql = "Select Component as Result from BOM_Explosion where TOP_MATERIAL = '-FHN7092A-EF' and ROWNUM <= 5;";
break;
}
try
{
Open();
OracleDataAdapter da = new OracleDataAdapter(sql, conn);
da.Fill(ds);
dt = ds.Tables[0];
}
catch (Exception ex)
{
}
finally
{
Close();
}
return dt;
}
}
And this is my WebMethod
[WebMethod]
public string ObtenerDatosNumeroParte()
{
DataTable dt = new DataTable();
dt = conn.ConsultarTablas("Datos");
Ticket ti;
List<Ticket> lista = new List<Ticket>();
for (int i = 0; i < dt.Rows.Count; i++)
{
ti = new Ticket();
ti.Vs = dt.Rows[i]["Result"].ToString();
lista.Add(ti);
ti = null;
}
JavaScriptSerializer js = new JavaScriptSerializer();
string lineas = js.Serialize(lista);
return lineas;
}
Testing it seems like my code do not execute my query and my List always is null, what I'm doing wrong and what can I do to solve it?
Update
Using my string canConnect I get ORA-6413: Connection not open.
I'm trying to get all data from an SQL table and store it in a List using the C# programming language.
the SQL statement I'm using is:
private string cmdShowEmployees = "SELECT * FROM Employees;";
This is being used in the same class as a function
public List<string> showAllIdData()
{
List<string> id = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
id.Add(reader[0].ToString());
}
return id;
}
}
and here
public List<string> showAllActiveData()
{
List<string> active = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
active.Add(reader[1].ToString());
}
return active;
}
I would have to create 9 more functions this way in order to get all the data out of the Employees table. This seems very inefficient and I was wondering if there was a more elegant way to do this.
I know using an adapter is one way to do it but I don't think it is possible to convert a filled adapter to a list, list list etc.
SqlDataAdapter adapter = sqlDataCollection.getAdapter();
DataSet dataset = new DataSet();
adapter.Fill(dataset, "idEmployees");
dataGridView1.DataSource = dataset;
dataGridView1.DataMember = "idEmployees";
Any ideas?
If you must use the reader in this way, why not create an object which holds the table row data.
public class SomeComplexItem
{
public string SomeColumnValue { get; set;}
public string SomeColumnValue2 { get; set;}
public string SomeColumnValue3 { get; set;}
public string SomeColumnValue4 { get; set;}
}
That way you can loop through with your reader as follows:
public List<SomeComplexItem> showAllActiveData()
{
List<SomeComplexItem> active = new List<SomeComplexItem>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
var someComplexItem = new SomeComplexItem();
someComplexItem.SomeColumnValue = reader[1].ToString();
someComplexItem.SomeColumnValue2 = reader[2].ToString();
someComplexItem.SomeColumnValue3 = reader[3].ToString();
active.Add(someComplexItem);
}
return active;
}
You could use two select statements to populate two List<string> as shown in the example below where the key between reads is reader.NextResult();.
The database used is the standard Microsoft NorthWind database.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
namespace SQL_Server_TwoList
{
public class DataOperations
{
public List<string> Titles { get; set; }
public List<string> Names { get; set; }
/// <summary>
/// Trigger code to load two list above
/// </summary>
public DataOperations()
{
Titles = new List<string>();
Names = new List<string>();
}
public bool LoadData()
{
try
{
using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
string commandText = #"
SELECT [TitleOfCourtesy] + ' ' + [LastName] + ' ' + [FirstName] As FullName FROM [NORTHWND.MDF].[dbo].[Employees];
SELECT DISTINCT [Title] FROM [NORTHWND.MDF].[dbo].[Employees];";
using (SqlCommand cmd = new SqlCommand(commandText, cn))
{
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Names.Add(reader.GetString(0));
}
// move on to second select
reader.NextResult();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Titles.Add(reader.GetString(0));
}
}
}
}
}
return true;
}
catch (Exception)
{
return false;
}
}
}
}
Form code
namespace SQL_Server_TwoList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataOperations dataOps = new DataOperations();
if (dataOps.LoadData())
{
listBox1.DataSource = dataOps.Names;
listBox2.DataSource = dataOps.Titles;
}
}
}
}
You could always add it all to a dataset or datatable instead of looping through using datareader to add to an array, dataset allows you to access data in similar way to array anyway.
Connstr = "Data Source = " + SelectedIP + "; Initial Catalog = " + dbName + "; User ID = " + txtUsername.Text +"; Password = "+ txtPassword.Text +"";
conn = new SqlConnection(Connstr);
try
{
string contents = "SELECT * FROM ..."
conn.Open();
SqlDataAdapter da_1 = new SqlDataAdapter(contents, conn); //create command using contents of sql file
da_1.SelectCommand.CommandTimeout = 120; //set timeout in seconds
DataSet ds_1 = new DataSet(); //create dataset to hold any errors that are rturned from the database
try
{
//manipulate database
da_1.Fill(ds_1);
if (ds_1.Tables[0].Rows.Count > 0) //loop through all rows of dataset
{
for (int i = 0; i < ds_1.Tables[0].Rows.Count; i++)
{
//rows[rownumber][column number/ "columnName"]
Console.Write(ds_1.Tables[0].Rows[i][0].ToString() + " ");
}
}
}
catch(Exception err)
{}
conn.Close();
}
catch(Exception ex)
{}
A few months ago I made a test program for a project and everything worked fine there.
Now I am working on the program itself, so I copied the code from the test program and
changed the the names of the columns,buttons etc. so it would fit the current program.
When I try to add something into the database it does nothing on the first click, on the
second pops up an error which says that the connection is open.. I really got no idea what's
the problem. I tried to check again if I made a mistake in a column name or the database name
but everything seems to be correct.
Note: I also have a function that show data from the database and it works without any problem.
private void InsertData()
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
Connection.Open();
DataAdd.ExecuteNonQuery();
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
string NewRowNum()
{
string Row = RowFind();
int CalcRow = int.Parse(Row) + 1;
Row = CalcRow.ToString();
return Row;
}
The connection that appears to be open is the one in the string RowFind().
Here are the other related things to the database:
public partial class frmShop : Form
{
System.Data.SqlClient.SqlConnection Connection;
public frmShop()
{
string DatabaseConnection = WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1;
Connection = new System.Data.SqlClient.SqlConnection();
Connection.ConnectionString = DatabaseConnection;
InitializeComponent();
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
Connection.Open();
SqlDataReader ReadSentence = null;
Int32 BinaryInt = Int32.Parse(txtBinaryString.Text);
string CommandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
SqlCommand Command = new SqlCommand(CommandString, Connection);
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
ReadSentence = Command.ExecuteReader();
while (ReadSentence.Read())
{
txtSentence.Text = (ReadSentence["Sentence"].ToString());
Fit = 1;
}
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You are getting errors because you are reusing the same connection Connection.Open(); several times.
Your method InsertData() is doing this 3 times in the same method.
You should create a new instance of the connection object and dispose it on your methods.
Using Statement are the way to go.
private void InsertData()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
Connection.Open();
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
DataAdd.ExecuteNonQuery();
//Connection.Close(); no need to close
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You can save one more connection if you store the row returned by RowFind()
string RowFind()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
//Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
So you would connect once instead of twice:
var Row = RowFind();
string NewCode = GenerateCode(Row);
string NewRow = NewRowNum(Row);
string NewSentence = txtSentence.Text;
Declare your connection string variable to a property so you can reuse it:
private string DatabaseConnection {get; set;}
Instead using an instance level SqlConnection you should only provide a common factory for creating a connection:
public partial class frmShop : Form
{
private string ConnectionString
{
get { return WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1; }
}
public frmShop()
{
InitializeComponent();
}
private SqlConnection CreateConnection()
{
var conn = new SqlConnection(ConnectionString);
conn.Open();
return conn;
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
using (var conn = CreateConnection())
{
var BinaryInt = int.Parse(txtBinaryString.Text);
var commandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
using (var Command = new SqlCommand(commandString, conn))
{
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
using (var readSentence = Command.ExecuteReader())
{
while (readSentence.Read())
{
txtSentence.Text = (readSentence["Sentence"].ToString());
Fit = 1;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void InsertData()
{
try
{
using (var conn = CreateConnection())
{
var commandString = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
using (var comm = new SqlCommand(commandString, conn))
{
comm.Parameters.AddWithValue("#NewBinaryString", GenerateCode());
comm.Parameters.AddWithValue("#NewNewSentence", txtSentence.Text);
comm.Parameters.AddWithValue("#NewRowNumber", NewRowNum());
comm.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
using (var conn = CreateConnection())
{
var commandString = "SELECT * FROM ShopSentences";
using (var comm = new SqlCommand(commandString, conn))
{
using (var sda = new SqlDataAdapter(queryString, Connection))
{
using (DataTable dt = new DataTable("ShopSentences"))
{
sda.Fill(dt);
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
}
}
}
string NewRowNum()
{
var Row = RowFind();
var CalcRow = int.Parse(Row) + 1;
return CalcRow.ToString();
}
}
But this is just the beginning you should not have any hard SQL dependency in your Form classes.
When sharing same SqlConnection instance several times in your code, instead of directly opening the you can rather check the connection state first and then open it if not already opened. For example:
if(Connection.State!= ConnectionState.Open)
Connection.Open();