I want to select file contains .txt and split all strings in each text into array
then insert the divided words into sql database (word, counter) and count the repeated words in each text by counter that lead to unrepeated words in database tables>>
(1)-counter code is incorrect I found several errors in my code >> (i want to prevent a repeat of word at the same time calculate how many times repeated word in databases ,by using counter.)
(2)- my code has static path (just one text ),but I want user to select his file which he want to split. (browse.. button)
(3-)sql database could not show Arabic Words (?????)
namespace lib123
{
public partial class Form1 : Form
{
SqlConnection sqlConn;
SqlCommand sqlComm;
SqlDataAdapter sqlAdptr;
public Form1()
{
InitializeComponent();
sqlConn = new SqlConnection();
sqlComm = new SqlCommand();
sqlAdptr = new SqlDataAdapter();
sqlComm.Connection = sqlConn;
sqlComm.CommandType = CommandType.Text;
sqlConn.ConnectionString = "Data Source=007-PC\\SQLEXPRESS ;Initial Catalog= Email_DB;Integrated Security =True ";
}
private void Form1_Load(object sender, EventArgs e)
{
FillGrid();
}
private void button1_Click(object sender, EventArgs e)
{
if (sqlConn.State != ConnectionState.Open)
sqlConn.Open();
// sqlComm = sqlConn.CreateCommand();
StreamReader streamReader = new StreamReader(#"C:\Users\007\Desktop\spam-email\spamenglish.txt"); //get the file
string stringWithMultipleSpaces = streamReader.ReadToEnd(); //load file to string
streamReader.Close();
Regex r = new Regex(" +"); //specify delimiter (spaces)
string[] words = r.Split(stringWithMultipleSpaces); //(convert string to array of words)
int c = 1;
string strQry = "select ISNULL( max(id),0) as id from word_tb ";
sqlComm.CommandText = strQry;
int LastID = int.Parse(sqlComm.ExecuteScalar().ToString());
string x ;
String st = null;
for (int i = 0; i < words.Length; i++)
{
string y = words[i];
for (int j = 0; j <LastID; j++)
{
x = "select word from word_tb where id = j";
sqlComm.CommandText = x ;
if (x.Equals(y))
{
c = c + 1;
string sql = "INSERT INTO word_tb (count) VALUES ('" + c + "') where id = i";
sqlComm.CommandText = sql;
}
else
{
LastID = LastID + 1;
st += "INSERT INTO word_tb(id, word,count) VALUES('" + LastID + "', '" + words[i].ToString() + "','" + c + "');";
//st += "INSERT INTO word_tb(word) VALUES('" + words[i].ToString() + "');";
}
}
}
sqlComm.CommandType = CommandType.Text;
sqlComm.CommandText = st;
sqlComm.ExecuteNonQuery();
FillGrid();
}
private void FillGrid()
{
DataTable tbl = new DataTable();
string strQry = "select * from word_tb ";
sqlComm.CommandText = strQry;
sqlAdptr.SelectCommand = sqlComm;
sqlAdptr.Fill (tbl) ;
dataGridView1.DataSource = tbl;
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
//private void btnDelete_Click(object sender, EventArgs e)
//{
// string str = "DELETE FROM word_tb";
// sqlComm.CommandType = CommandType.Text;
// sqlComm.CommandText = str;
// sqlComm.ExecuteNonQuery();
// dataGridView1.Rows.Clear();
// }
}
}
1-counter code is incorrect I found several errors in my code?
you can use below code to split the File Text into words based on space as delimiter.
Code:
String strAllData = System.IO.File.ReadAllText(#"C:\Users\007\Desktop\spam-email\spamenglish.txt");
String[] words = strAllData.Split(' ');
2- my code has static path (just one text ),but I want user to select
his file which he want to split. (browse.. button) ?
you can use OpenFileDialog control to let user choose the file which he/she wants to work on.
Code:
OpenFileDialog fileDialog = new OpenFileDialog();
if (fileDialog.ShowDialog() == DialogResult.OK)
{
String strAllData = System.IO.File.ReadAllText(fileDialog.FileName);
String[] words = strAllData.Split(' ');
}
3 -sql database could not show Arabic Words (?????) ?
Sql Server can not show Uni Code characters when you fire a SELECT Query because you have created your table columns/feilds as varchar.
Solution: if you want to get the Arabic characters when you fire a SELECT query you should create your table columns to accept Uni Code characters using NVARCHAR datatype instead of VARCHAR. N stands for National language character set.
Step1 : create your table columns as NVARCHAR as below:
create table sample(
[name] [nvarchar](100) NOT NULL)
Step 2: Use N as prefix while inserting Data into NVARCHAR columns. N as prefix tells that all following characters are Uni Code characters.
Code:
INSERT INTO sample VALUES(N'لا أتكلم العربية');
Now if you fire a SELECT Query you will be able to see the Arabic Characters.
Related
I'm a newbie when it comes to C#, but have some experience with C, Python and MATLAB. I wrote a simple C# program that takes in some user input and converts it into a (parameterized) SQL query. I've successfully converted the datetimepicker into a SQL query; however, I have another parameter (serial numbers) that the user would input into a textbox. They can enter multiple serial numbers, separated by commas. Once the user clicks on 'Submit', the SQL query is sent and the results displayed in a dataGridView.
It works with a single value (i.e. a single serial number), but when I try to put in multiple values, it doesn't work.
I've tried some suggestions like separating the textbox string into an array of values.
private DataTable GetResults()
{
DataTable dtResults = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (SqlConnection con = new SqlConnection(connString))
{
using (SqlCommand cmd = con.CreateCommand())
{
string[] numbers = textBox2.Text.Split(',');
var parameters = new string[numbers.Length];
for (int i = 0; i < numbers.Length; i++)
{
parameters[i] = string.Format("#SN{0}", i);
cmd.Parameters.AddWithValue(parameters[i], numbers[i]);
}
cmd.CommandText = string.Format("SELECT [TestDate],[ParamName],[SerialNumber],[TestDataID],[MeasuredValue]," +
"[MaximumLimit],[MinimumLimit],[PassResult] FROM [dbo].[Device.ParametricTestResults] " +
"WHERE SerialNumber IN ({0}) " +
"AND (TestDate BETWEEN (#start) AND (#end)) " +
"AND PassResult = 1", string.Join(", ", parameters));
cmd.Parameters.AddWithValue("#start", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#end", dateTimePicker2.Text);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dtResults.Load(reader);
}
}
return dtResults;
}
And the 'Submit' button has the following code attached to it:
private void button12_Click(object sender, EventArgs e)
{
TestResultsdataGridView.DataSource = GetResults();
}
Again, the datagridview should display entries for multiple serial numbers, but it only works for one.
I need to load data from text file/csv file to a SQL Server database. I used the code shown below to load data and is loading to the database the problem is the data in second column may contain space but I use space for separate the column data.
i.e.
200007 XXXX Check XXXX yyy 50
200013 YYYY Check ZZZZ yyy 50
200022 nnnn 25Mg 30 Tabs
200042 mmmm 30 Mg 30 Tabs
I need to store the first ID number in the first column and the remaining text in second column:
string str = Properties.Settings.Default.con;
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = con;
con.Open();
cmd.CommandText = "IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='TEMP_AUTO' AND xtype='U')" +
"CREATE TABLE TEMP_AUTO (" +
"ID varChar(10) NULL," +
"NAME varChar(50) NULL," +
"DATE TIMESTAMP NULL," +
")";
cmd.ExecuteNonQuery();
string query1 = "INSERT INTO [dbo].[TEMP_AUTO]([ID],[NAME]) VALUES (#num1, #num2)";
cmd.CommandText = query1;
string[] allLines = File.ReadAllLines(txtFilePath.Text);
for (int i = 0; i < allLines.Length; i++)
{
cmd.Parameters.Clear();
string[] items = allLines[i].Split(new char[] { ' ' });
cmd.Parameters.AddWithValue("#num1", items[0]);
cmd.Parameters.AddWithValue("#num2", items[1]);
cmd.ExecuteNonQuery();
}
MessageBox.Show("Successfully saved your data");
}
finally
{
cmd.Dispose();
con.Close();
}
A possible solution might be this:
string[] allLines = {
"200007 XXXX Check XXXX yyy 50",
"200013 YYYY Check ZZZZ yyy 50",
"200015 ",
"2541111"
};
for (int i = 0; i < allLines.Length; i++)
{
string param1 = null;
string param2 = null;
int spaceIndex = allLines[i].IndexOf(' ');
if (spaceIndex > 0)
{
param1 = allLines[i].Substring(0, spaceIndex);
if (spaceIndex < allLines[i].Length - 1)
{
param2 = allLines[i].Substring(spaceIndex + 1, allLines[i].Length-1 - spaceIndex);
}
}
else
{
param1 = allLines[i];
}
Console.WriteLine("param1:{0} param2:{1}", param1, param2);
}
Use SSIS to map this file as long as it has a standard structure to SQL Table.
Is this a one time thing? Have you tried getting the data organized in Excel then using the SSMS import tool to bring it in? If you right click on the Database then Tasks > Import Data the wizard will appear when given the option to choose the source, choose Excel. Flat files is an option but if you can format it in Excel first that tends to work better.
As you click through you can adjust the column types and where the breaks are, much like importing into Excel itself.
Use the String.Split(Char[], Int32) method to split on the first occurrence of ' ' only. Eg
string[] items = allLines[i].Split(new char[] { ' ' }, 2);
Refs: MSDN and previous relevant question
Use the below code.
using (StreamReader sr = File.OpenText("txtFile.txt")) // Mention the path,if the file is not in application folder.
{
string str = String.Empty;<br/>
while ((str = sr.ReadLine()) != null)
{
string[] item = str.Split(' ');
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand();
string query1 = "INSERT INTO [dbo].[TEMP_AUTO]([ID],[NAME]) VALUES ('" + item[0] + "', '" + item[1] + "')";
// Do remain part<br/>
}
}
I have a single TextBox and a search button. The user put multiple comma separated values in a single TextBox (ex. 111,222,333), which are stored in one column (ID), then fetch all the records in the grid view by an MS Access table.
Table name: mytable
Fields:
ID name phno
111 saket 8097626799
222 deepak 9167480458
333 abhi 9229457891
444 rajesh 9826789561
555 sudhir 9167849503
Output:
ID name phno
111 saket 8097626799
222 deepak 9167480458
333 abhi 9229457891
The following does assertion on text within a text box, see comments. The variable whereCondition will contain the sample SQL statement if all assertion/validation passes.
private void button1_Click(object sender, EventArgs e)
{
string whereStatement = "";
// ensure we have something to work with
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
// Are there commas
if (textBox1.Text.Contains(","))
{
string textValue = textBox1.Text.TrimEnd();
// make sure there is no trailing commas
if (textValue.Last() != ',')
{
string[] parts = textBox1.Text.Split(',');
int badCount = 0;
int testValue = 0;
// see if all values are int
foreach (string item in parts)
{
if (!int.TryParse(item, out testValue))
{
badCount += 1;
}
}
if (badCount == 0)
{
string whereCondition = "ID = " + textValue.Replace(",", " OR ID = ");
whereStatement = string.Format("SELECT [Name], phno WHERE {0} FROM mytable", whereCondition);
}
}
}
else
{
// one id
whereStatement = string.Format("SELECT [Name], phno WHERE ID = {0} FROM mytable", textBox1.Text);
}
}
if (!string.IsNullOrWhiteSpace(whereStatement))
{
MessageBox.Show(whereStatement);
}
else
{
MessageBox.Show("Invald data");
}
}
I HAVE ANOTHER CODE
ITS WORKING
c# CODE
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
protected void Search(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
//string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string constr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\WebSite1\App_Data\MPHS.mdb";
using (OleDbConnection con = new OleDbConnection(constr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
string resultCont = string.Empty;
if (!string.IsNullOrEmpty(txtSearch.Text))
{
string[] contactNames = txtSearch.Text.Trim().Split(',');
foreach (string cont in contactNames)
{
if (!string.IsNullOrEmpty(cont))
{
resultCont = resultCont + ",'" + cont + "'";
}
}
resultCont = resultCont.Remove(0, 1);
cmd.CommandText = "SELECT * FROM myTable WHERE Docnum IN (" + resultCont + ")";
}
else
{
cmd.CommandText = "SELECT * FROM myTable";
}
DataTable dt = new DataTable();
using (OleDbDataAdapter sda = new OleDbDataAdapter(cmd))
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
i am doing a search from database. user will enter string. this string will be converted into array then this array indexed values will be checked from table to find the match.
I am using loop to traverse array query execution is in that loop, it searches fine but if there was more than one index to search it shows the last index searched values.
i know know that's not a proper way to search.
how can i do this.
SqlConnection conOpen;
string[] arrayList;
protected void Page_Load(object sender, EventArgs e)
{
DataLayer datalayer = new DataLayer();
conOpen = datalayer.connectionOpen();
string myString = Request.QueryString["searchText"].ToString();
char[] separator = new char[] { ' ' };
arrayList = myString.Split(separator);
for (int i = 0; i <= arrayList.GetUpperBound(0); i++)
{
Response.Write(arrayList[i]);
string asd = arrayList[i];
String arrayQuery = "Select * from tbl_products where product_name LIKE '%" + #asd + "%'";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(arrayQuery, conOpen);
da.Fill(ds, "tbl_products");
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
I'm too clear on what your final result is supposed to be but I'm going to guess. I think what you are asking is that you want the query to search for every instance of the search items (seperated by a space) the users put in the input element and return ALL of these findings to your GridView. Ok. So I would suggest you loop to "build" your sql statement and then run the sql and bind the data AFTER the loop (not during).
One more important element is that you should most definitely parametrize these values since it's coming from user input in order to prevent SQL-Injection. Please forgive any typos (it is late).
DataLayer datalayer = new DataLayer();
conOpen = datalayer.connectionOpen();
string myString = Request.QueryString["searchText"].ToString();
char[] separator = new char[] { ' ' };
arrayList = myString.Split(separator);
StringBuilder arrayQuery = new StringBuilder();
SqlCommand myCommand = new SqlCommand();
for (int i = 0; i < arrayList.Length; i++)
{
if (i==0)
{
arrayQuery.Append("Select * from tbl_products where product_name LIKE #asd" + i);
} else{
arrayQuery.Append(" OR product_name LIKE #asd" + i );
}
myCommand.Parameters.AddWithValue("#asd" + i, "%" + arrayList[i] + "%");
}
myCommand.CommandText = arrayQuery.ToString();
myCommand.Connection = conOpen;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(myCommand);
da.Fill(ds, "tbl_products");
GridView1.DataSource = ds;
GridView1.DataBind();
i have the code of passing a selected value in the the query and that value will bind the data in the girdview. the selection is made with the Listbox..
I want to pass a list param of S_ID
Now I want to modify my program a little i want to pass a list of param. in the query.. so that this can enable multiple selection list in the listbox.. I've searched over Internet and i couldnt find a certain satisfying answer... I'm not very good at query.
protected void Button2_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database11.accdb";
con.Open();
for (int i = 0; i < ListBox1.Items.Count; i++)
//foreach(Items Item in Listbox1)
{
if (ListBox1.Items[i].Selected == true)
{
string Skill_ID = ListBox1.Items[i].Value;
string query1 = "SELECT *FROM Emp AS E, Junction AS J WHERE E.E_ID=J.E_ID And J.S_ID=#Skill_ID";
OleDbCommand cmd1 = new OleDbCommand(query1, con);
cmd1.Parameters.AddWithValue("#Skill_ID", Skill_ID);
OleDbDataReader rs = cmd1.ExecuteReader();
if (rs.HasRows)
{
GridView1.DataSource = rs;
GridView1.DataBind();
rs.Close();
}
//use LINQ to obtain the selected id values as strings
var selectedItems = ListBox1.Items.Cast<ListItem>().Where(p => p.Selected == true).Select(p => p.Value).ToList();
//now concat them as a comma seperated string
var idCommaList = string.Join(', ', selectedItems);
//Now use a WHERE IN () statement instead with your query and concat your comma seperated list of ids into the sql statement
var query1 = #"SELECT *
FROM Emp AS E, Junction AS J
WHERE E.E_ID = J.E_ID AND J.S_ID IN (" + idCommaList + ")";