I am working on sharp nlp where i am extracting all the adjective now i need to store this in database and i have successfully added this to database but the problem is with me that i want to store adjective separately to database how can i store the adjective separately or for example we have string and we want to store each word separately into database and we have only one column how can we do this? .please help me out
here is my code.
private void button2_Click(object sender, EventArgs e)
{
try
{
string cleaned = richTextBox1.Text.Trim();
string st = "INSERT INTO TABLE1(adjective)VALUES('" + cleaned + "')";
SqlConnection con = new SqlConnection("Data Source=ZAZIKHAN\\SQLEXPRESS;Initial Catalog=mis;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(st, con);
if (cmd.ExecuteNonQuery() == 1)
{
MessageBox.Show(" succesfully added");
}
else
{
MessageBox.Show("Sorry we couldnt add the Values Please try Again");
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
now i have this data to be stored which is in richtextbox.
local/JJ daily/JJ n/price/rate/JJ human/JJ possible/JJ correct/JJ exact/JJ local/JJ
local/JJ daily/JJ n/price/rate/JJ human/JJ possible/JJ correct/JJ exact/JJ local/JJ
dry/JJ nd/JJ
new/JJ full/JJ OK/JJ final/JJ white/JJ OK/JJ howajaa/JJ smajder/JJR agaa/JJ nasambd/JJ Live/JJ
final/JJ
great/JJ s3/JJ final/JJ
resistant/JJ Z1/JJ white/JJ new/JJ black/JJ amaa.Kintact/JJ possible/JJ main/JJ mobile/JJ rapak/JJ mil/JJ
important/JJ mil/JJ smart/JJ
35-h/JJ OK/JJ full/JJ
Want/JJ complete/JJ white/JJ same/JJ
available/JJ perfect/JJ
interested/JJ
First off, the lines
string cleaned = richTextBox1.Text.Trim();
string st = "INSERT INTO TABLE1(adjective)VALUES('" + cleaned + "')";
create a massive security hole known as SQL Injection.
In order to store the adjectives separately in a properly denormalized database, you would have a parent table where e.g. the original sentence is stored, and a child table with a 1:N relationship to the parent where you store one row per adjective plus the appropriate ID of the parent row.
Since you only have one column available, you can use any convenient format to store the array of adjectives in a single column. You could serialize that array (to Binary, XML, JSON, etc) and store it, or since you know you have a limited input character set, you could even store it as a comma separated list.
You can prefix your words with some characters to indicate whether they are verb , noun , adjective and tehn insert those value in database
eg
N_JonSkeet - Noun
V_Solve - Verb
A_Highest - Adjective
string cleaned = extractAdjective(richTextBox1.Text.Trim());
string st = "INSERT INTO TABLE1(word) VALUES(#Word)";
SqlConnection con = new SqlConnection("Data Source=ZAZIKHAN\\SQLEXPRESS;Initial Catalog=mis;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(st, con);
SqlParameter param = new SqlParameter("#Word", SqlDbType.NChar);
param.Value = "A_"+cleaned;
cmd.Parameters.Add(param);
I would separate the string into a list and then iterate over the list and insert into your DB:
var vals = "local/JJ daily/JJ n/price/rate/JJ human/JJ possible/JJ...";
var results = vals.Replace(" ", "")
.Replace("/JJ", "|")
.Replace("/", "|")
.Split('|')
.Distinct();
while(var result in results)
{
// DO insert here
}
Related
So I tried making a code for adding 2 same data within 2 different tables which is
"studentinfo" and "logindb"
I tried doing this
enter code heprivate void buttonRegisterStudent_Click(object sender, EventArgs e)
{
String connection = "server=localhost;user id=root;password=root;persistsecurityinfo=True;database=votingdb";
//Inserting Data
String insertDataInfo = #"INSERT INTO studentinfo (firstname,lastname,username,password,email) values
('"+this.textBoxFirstName.Text+"','"+this.textBoxLastName.Text+"','"+this.textBoxUsername.Text+
"','"+ this.textBoxPassword.Text + "','"+ this.textBoxEmail.Text + "')";
String insertDataLogin = #"INSERT INTO logindb (username,password) values ('"+this.textBoxUsername.Text+"','"
+this.textBoxPassword.Text+"')";
//Connection
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand datainfo = new MySqlCommand(insertDataInfo,con);
MySqlCommand datalogin = new MySqlCommand(insertDataLogin, con);
MySqlDataReader datareaderinfo;
MySqlDataReader datareaderlogin;
try
{
con.Open();
datareaderinfo = datainfo.ExecuteReader();
datareaderlogin = datalogin.ExecuteReader();
MessageBox.Show("Student Register Successfully!");
}
catch (Exception ex)
{
MessageBox.Show("Failed to Register" + ex);
}
}
Resulting to Error which says there may only one mysqldatareader in the code. How can I add the same data to the different tables?
Don't use a datareader if you don't want to read data. Simple use the ExecuteNonQuery on your command:
datainfo.ExecuteNonQuery();
And don't forget to open en close your connection!
You don't need a data reader for insert statements, you should simply use ExecuteNonQuery.
Please note that your current queries are a security hazard as they are vulnerable to SQL Injection attacks.
Instead of concatenating user inputs as strings to create your SQL statements, use parameterized queries.
For more information, read How can prepared statements protect from SQL injection attacks?
An improved version of the main parts in your code is this:
var insertDataInfo = #"INSERT INTO studentinfo (firstname,lastname,username,password,email) values
(#firstName, #lastName, #userName, #passwordHash, #email)";
var insertDataLogin = #"INSERT INTO logindb (username,password) values (#userName, #passwordHash)";
var datainfo = new MySqlCommand(insertDataInfo,con);
datainfo.Parameters.Add("#firstName", DbType.VarChar).Value = this.textBoxFirstName.Text;
datainfo.Parameters.Add("#lastName", DbType.VarChar).Value = this.textBoxLastName.Text;
datainfo.Parameters.Add("#userName", DbType.VarChar).Value = this.textBoxUsername.Text;
datainfo.Parameters.Add("#passwordHash", DbType.VarChar).Value = this.textBoxPassword.Text;
datainfo.Parameters.Add("#email", DbType.VarChar).Value = this.textBoxEmail.Text;
var datalogin = new MySqlCommand(insertDataLogin, con);
datalogin.Parameters.Add("#userName", DbType.VarChar).Value = this.textBoxUsername.Text;
datalogin.Parameters.Add("#passwordHash", DbType.VarChar).Value = this.textBoxPassword.Text;
datainfo.ExecuteNonQuery();
datalogin.ExecuteNonQuery();
Also, you are storing passwords as plain text in your database.
That's a really big security hole. You should be storing salted hash values of your passwords instead - but that's getting a little too broad for this answer so I'll leave that part up for you to read and apply.
I am working on a project where the user gets to generate a set of licenses keys and export it into a text file. The information is then displayed in a listbox as shown below. I am using C# and Windows Forms:
On top of this I would also like to save the details from the listbox into the local SQL Server database for record keeping purposes in my application. I have tried out various methods I found online to do this but all were unsuccessful.
One of the methods I've found is from this link:
https://www.youtube.com/watch?v=hUZGyA6UKGI&t=0s&index=26&list=PLZEMJ7iJtVdq9aMAiDfRlMoNrzGaWOfkZ
Here is the code I used from the video tutorial:
private void recordinserted(List<string>li)
{
StringBuilder stringbi = new StringBuilder(string.Empty);
foreach (string item in li)
{
const string qry = "Insert into [LicenseDB](Comapny Name, Software Name, LicenseKeys)values";
stringbi.AppendFormat("{0}('{i}');",qry,item);
}
SqlConnection con = new SqlConnection();
con.ConnectionString = (#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Documents\Database.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = stringbi.ToString();
cmd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("inserted");
}
}
// adding into local database (method placed in button click)
List<string> li = new List<string>();
foreach (ListViewItem item in lbGeneratedKeys.Items)
{
if (item.Selected)
{
li.Add(item.Text);
}
recordinserted(li);
}
I realized that the person was using C# with ASP.Net and makes use of ListITem property which Windows Form does not have.
The other method I used is the classic SqlConnection method:
//adding into local database
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Documents\Database.mdf;Integrated Security=True;Connect Timeout=30"))
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO LicenseDB (Company Name, Software Name, LicenseKeys,LicenseFileNo) VALUES (#cName, #sName, #lKeys, #lno)");
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lbGeneratedKeys.Items.Add(dr[0].ToString());
lbGeneratedKeys.Items.Add(dr[1].ToString());
lbGeneratedKeys.Items.Add(dr[2].ToString());
lbGeneratedKeys.Items.Add(dr[3].ToString());
}
}
I used (dr[0].ToString()) to read each line from the listbox to be added into the database, where each number represents a row in the listbox. Eg. [0] represents the company name in the listbox. However when I try to execute the program there's an error saying that the SqlDataReader row is not initialized.
Also, since my program has the algorithm for users to generate more than one license keys, I also need help on how I can group these several rows of generated license keys to be added into one database column in the Database table. For instance in my UI above, I chose to generate 3 license keys and each license key takes up a row in the ListBox, I would like to group these three rows together to be placed under one database column variable (licenseKeys). I would like the algorithm to be able to read the generated keys dynamically as well as the user can generate as many license keys as needed.
I hope I had understood your problem:
First of all, I think is very important to define your data model. For example, in order to allow that a user can define a lot of keys, I would use another table where all the keys were stored, after that you need to define if a same key could be related to more than one row on the table 'LicenseDB' (in the table 'LicenseDB' you would have the columns Company Name, Software Name, LicenseFileNo). If so you'd have the relation (n:n) and then you would need to build another intermediate table that defines the relation between the table 'keys' and the table 'LicenseDB' . If it's not the case, then you simple define the relation between 'keys' and 'LicenseDB' (n:1) adding a column licenseDbID to the table 'keys' that relation many keys to one row in the table 'LicenseDB'
On the other hand, the problem with your code is that you are trying to insert data and not to read data, so you don't need a DataReader instead of that you just simply could implement something like this:
using (SqlConnection con = new SqlConnection('YOUR STRING CONNECTION'))
{
con.Open();
string comando = "INSERT INTO LicenseDB (companie, software) VALUES ('" + lbGeneratedKeys.Items[0].ToString() + "','" + lbGeneratedKeys.Items[1].ToString() + "')";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = comando;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
In this case, two values are inserted into the table LicenseDB the values for companie name and software name.
I hope I had helped you.
I referred back to my previous school project and managed to save my listbox data into the SQL database. I have two listboxes in total: 1 for allowing user to export as text file, and the second to specifically store generated license keys only. The second listbox is set to not visible in my program.
The codes I used:
private void exportKey_Click(object sender, EventArgs e)
{
//adding into local database
//excludes adding licensekeys
SqlConnection sqlCon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Documents\Database.mdf;Integrated Security=True;Connect Timeout=30");
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("addLicensedata", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue(#"companyName", companyTextbox.Text.Trim());
sqlCmd.Parameters.AddWithValue(#"softwareName", softwareTextbox.Text.Trim());
sqlCmd.Parameters.AddWithValue(#"prodID", prodidTextbox.Text.Trim());
sqlCmd.Parameters.AddWithValue(#"licenseType", cbLicensetype.Text.Trim());
sqlCmd.Parameters.AddWithValue(#"LicenseNo", licensekeyNum.Text.Trim()); //no of license keys
sqlCmd.ExecuteNonQuery();
//MessageBox.Show("Added to database");
sqlCon.Close();
if (cbLicensetype.SelectedItem.ToString() == "Trial")
{
sqlCmd.Parameters.AddWithValue(#"TrialDays", tbTrialdays.Text.Trim());
}
addtoFKtable();
private void addtoFKtable()
{
SqlConnection Con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Documents\Database.mdf;Integrated Security=True;Connect Timeout=30");
Con.Open();
SqlCommand Cmd = new SqlCommand("addLicensekeys", Con);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.AddWithValue(#"LicenseNo", licensekeyNum.Text.Trim());
Cmd.Parameters.AddWithValue(#"LicenseKeys", lbHidden.Text.Trim());
Cmd.Parameters.AddWithValue(#"prodID", prodidTextbox.Text.Trim());
Cmd.Parameters.AddWithValue(#"companyName", companyTextbox.Text.Trim());
Cmd.ExecuteNonQuery();
//MessageBox.Show("Added license to database");
Con.Close();
}
I stored my SQL commands as a stored procedure within the database, and just called the command in my codes.
I'm developing a website for a parent association, for a school. My system has two reserved areas, which parents and also teachers/school members has access. These two areas, are the backoffice and the FrontOffice.
I can begin a new session with a dad or mother username, and their respective password, and then in frontoffice i've a new page where, it was supossed, a new meal be sucessfully done reserved and in result of that a new row should be inserted in a SQL database table.
It happens that for this, i've next code:
protected void ReserveMeal (object sender, EventArgs e)
{
string tipoRefeicao=string.Empty;
DateTime DataSelecionada = Convert.ToDateTime(BasicDatePicker1.Text.ToString());
bool refeicaoFinalizada = false; //Refeicao nao é consumida no imediato
try
{
//ligar a base de dados e realizar nova conexao
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Vitor\Documents\Visual Studio 2015\Projects\Educational\Educational\App_Data\SchoolPASS.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
string selectUser = "SELECT count (*) from EEAluno where NomeUtilizadorEE='" + newName + "'";
string res = Convert.ToString(selectUser);
SqlCommand com = new SqlCommand(selectUser, con);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
con.Close();
if (temp == 1)
{
con.Open();
string verificaPassword = "select Password from EEAluno where NomeUtilizadorEE='" + newName + "'";
SqlCommand passCommand = new SqlCommand(verificaPassword, con);
string password = passCommand.ExecuteScalar().ToString();
if (password == Session["Pass"].ToString())//Nao testado
{
//Inserir refeicao numa tabela nova
SqlCommand insert = new SqlCommand("INSERT INTO TabelaRefeicoesEncomendadas (NomePessoa,TipoRefeicao,Data, Finalizada) VALUES (#NomePessoa,#TipoRefeicao,#Data,#Finalizada)", con);
//insert.Parameters.Add("#Id", 1);
insert.Parameters.AddWithValue("#NomePessoa", newName);
insert.Parameters.AddWithValue("#TipoRefeicao", tipoRefeicao);
insert.Parameters.AddWithValue("#Data", DataSelecionada);
insert.Parameters.AddWithValue("#Finalizada", refeicaoFinalizada);//escreve falso na DB
}
}
}
catch (Exception exc)
{
}
}
Doing a carefully analysis, in code, you could observe that i'm, trying to check if the autenticated user is the correct user.
So if we have many users inside a DB table, only one, only for example "X" (i assumed that "X" has sucessfully logged into system), is the active user, in a determined computer, and only "X" could reserve a meal for the respective children.
Resume: I've thinked in a algorithm to check the user session, and then insert a reserved meal, into a database table. I did not succeed. I think it can not verify correctly the sessions. Two errors exist.
Every time that i try to create the meal (when method is called), the username is incremented, so if username is "X" username becomes "XX"
The information about meal is not inserted into SQL database.
Could you help me!
Based on the code snipped provided, you are not executing the sql command for the insert.
Something like this should work, after you are done setting up the parameters:
insert.ExecuteNonQuery();
I am trying to save a value from text box into sql database. I am having the error as shown on the picture. my code below:
public void datastore()
{
string Blerje, Shitje, Data;
Blerje = usdollar_buy.Text;
Shitje = usdollar_sell.Text;
Data = dateTimePicker.Text;
try
{
string constring = "Data Source=DELL;Initial Catalog=login_register;Integrated Security=True";
/* Declaring Connection Variable */
SqlConnection con = new SqlConnection(constring);
String sql = "INSERT into [login_register].[dbo].[BlerjeShitje] values ('" + Blerje + "','" + Shitje + "','" + Data + "')";
/* Checking Connection is Opend or not If its not open the Opens */
if (con.State != ConnectionState.Open)
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
/* Executing Stored Procedure */
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Te dhenat u ruajten ne databaze");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
1. You might be having more columns in your table than mentioned values(3) in your query.
so it is always good to specify the column names in your query for which columns you are inserting the values.
Try This:
INSERT INTO [TableName](COL1,COl2,COL3)
Values(Value1,Value2,Value3);
2. As you mentioned your columsn are decimals, you are inserting them as as strings by enclosing the values within single quotes.
You should not enclose the decima values within single quotes.
Suggestion : Your query is open to SQL Injection Attacks.
I Would suggest you to use the Parameterised queries to avoid them.
You are missing the fields in your insert statement.
The database will try to determine the right columns and their order, but if you don't deliver all fields in the appropriate order, your query will fail.
So in short:
Deliver all fields in the correct order;
Or: add the fields you want to fill in the insert.
Sample:
String sql = "INSERT into [login_register].[dbo].[BlerjeShitje] (Blerje, Shitje, Data) values ('" + Blerje + "','" + Shitje + "','" + Data + "')";
change the datatype to (18,6) or so, whichever is suitable for you,
The second part of decimal data type shows how many digits do you require after the 'point'. In your case it's '0', so db is rounding it to nearest integer.
Source: http://msdn.microsoft.com/en-us/library/ms187746.aspx
I have a bunch of 2 line (with header row) '|' delimited text files. I need to import this into a specific SQL table and I'm having a hard time with the command.
string sqltable = ("dbo.SLT_C" + "60" + "Staging");
string[] importfiles= Directory.GetFiles(#"K:\jl\load\dest", "*.txt")
SqlConnection con = new SqlConnection("Data Source=" + "Cove" + ";Initial Catalog=" + "GS_Ava_MCase"+ ";Integrated Security=" + "SSPI");
con.Open();
foreach (string importfile in importfiles)
{
}
or maybe I am going about this the whole wrong way.
You could look at a ready-made solution, like FileHelpers. This FREE library allows you to define the structure of your file by means of a class describing the fields in your file, and then you can easily load the whole file into an array of that class type.
Once that's done, just simply iterate through the objects, and save them to your SQL Server.
Or check out the SQL Bulkcopy options:
bcp command line utility
SqlBulkCopy class in ADO.NET - also see this article at SQL Team
If you want to do it in "straight" ADO.NET, use something like this approach:
string sqltable = "dbo.SLT_C60Staging";
string[] importfiles = Directory.GetFiles(#"K:\jl\load\dest", "*.txt");
// try to wrap your ADO.NET stuff into using() statements to automatically
// dispose of the SqlConnection after you're done with it
using(SqlConnection con = new SqlConnection("Data Source=Cove;Initial Catalog=GS_Ava_MCase;Integrated Security=SSPI"))
{
// define the SQL insert statement and use parameters
string sqlStatement =
"INSERT INTO dbo.YourTable(DateField, TimeField, TextField) VALUES(#Date, #Time, #Text)";
// define the SqlCommmand to do the insert - use the using() approach again
using(SqlCommand cmd = new SqlCommand(sqlStatement, con))
{
// define the parameters for the SqlCommand
cmd.Parameters.Add("#Date", SqlDbType.DateTime);
cmd.Parameters.Add("#Time", SqlDbType.DateTime);
cmd.Parameters.Add("#Text", SqlDbType.VarChar, 1000);
// loop through all files found
foreach (string importfile in importfiles)
{
// read the lines from the text file
string[] allLines = File.ReadAllLines(importfile);
con.Open();
// start counting from index = 1 --> skipping the header (index=0)
for (int index = 1; index < allLines.Length; index++)
{
// split up the data line into its parts, using "|" as separator
// items[0] = date
// items[1] = time
// items[2] = text
string[] items = allLines[index].Split(new char[] { '|' });
cmd.Parameters["#Date"].Value = items[0];
cmd.Parameters["#Time"].Value = items[1];
cmd.Parameters["#Text"].Value = items[2];
cmd.ExecuteNonQuery();
}
con.Close();
}
}
}
That should work - you're question was too vague to know exactly what data will be in the lines, and what kind of SQL insert statement you'd need...
Using the text ODBC driver might work as well. In the ODBC administrator, you can choose the "Microsoft Access Text Driver". It allows you to choose the delimiter type. After setting up the data source, import to a data table. From there, it should be fairly simple to move the data into a SQL Server table.