Add listbox item to SQL Server columns as columns name - c#

foreach (string LB in listBox1.Items)
{
SqlCommand SCA = new SqlCommand("create table " + textBox3.Text + "("+
listBox1.Items[].ToString()+")",SC1);
SCA.ExecuteNonQuery();
}
How to add all items using loop to add items on listbox.items to SQL Server columns for columns name only?
Example:

You are trying to create several tables with the same name in a loop. I suppose your code should look something like that:
// StringBuilder is better way to creating a string in a loop,
// because it doesn't allocate new string on each concatenation
StringBuilder command = new StringBuilder("create table ");
command.Append(textBox3.Text).Append("(");
string separator = "";
// It is better to give more descriptive names to variables
foreach (string columnName in listBox1.Items)
{
// You forgot to specify column type
command.Append(separator)
.Append(columnName)
.Append(" varchar(1000)");
separator = ",";
}
command.Append(")");
// SqlCommand and SqlConnection implement IDisposable,
// so it is better to wrap their instantiation by 'using' statement
// in order to free corresponding resources
using (SqlCommand sqlCommand = new SqlCommand(command.ToString(), SC1)) {
sqlCommand.ExecuteNonQuery();
}

Related

How to insert a ICollection<string> into one Field in ADO.NET?

I have ICollection object in my controller. This collection posted from view like this;
{string[3]}
[0]=a
[1]=b
[2]=c
public ActionResult TarifEkle(Tarifler tarif, ICollection<string> tAdim)
{
string mainconn = ConfigurationManager.ConnectionStrings["Tarif"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "insert into [NePisirsem].[dbo].[Tarifler](tAdim) values (#builder)";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlconn.Open();
I change this value like this a,b,c with my builder;
var builder = new System.Text.StringBuilder();
foreach (string item in tAdim)
{
builder.Append(item).Append(",");
sqlcomm.Parameters.AddWithValue("#builder", tarif.tAdim);
}
It works values are successfully became i want (a,b,c) but I can't add this values this way a,b,c
sqlcomm.Parameters.AddWithValue("#builder", tarif.tAdim); this code takes always just first value a not all of them.
How can i do?
You need tho change the following section
var builder = new System.Text.StringBuilder();
foreach (string item in tAdim)
{
builder.Append(item).Append(",");
sqlcomm.Parameters.AddWithValue("#builder", tarif.tAdim);
}
to
sqlcomm.Parameters.AddWithValue("#builder", string.Join(",", tAdim));
#builder will then be replaced by a,b,c in your sqlquery if you need a, b, c replace "," with ", ". Read more about string.Join() here.
Don't use AddWithValue()
As you can read here, you should prefere Parameters.Add() over Parameters.AddWithValue() as you can specify the appropriate SqlDbType that your string is converted to.
sqlcomm.Parameters.Add("#builder", SqlDbType.VarChar, 30).Value = string.Join(",", tAdim);
Either use SqlDbType.VarChar or SqlDbType.NVarChar and replace 30 with your actual max lenght.
INSERT INTO Statement
As explained here, the format of an insert statement looks like this:
INSERT INTO table_name (column_list)
VALUES
(value_list_1),
(value_list_2),
...
(value_list_n);
column_list is a list of Columns that in your case are on [NePisirsem].[dbo].[Tarifler] e.g. tAdim. Then multiple value_lists can be supplied, each generating a new row in your table. value_list needs to match the order of column_list

How do I add records to a table from a text file?

I have a table called statelist that looks like this:
abbrev nvarchar(2);
name nvarchar(50);
I have a text file called state_list.txt which has a list of states in this format:
'AL','Alabama'
'AK','Alaska'
'AR','Arkansas'
I want to get the data from the text file into the statelist table. Is there some kind of SQL Insert or other code to do this?
Well you didnt specify things like your database etc but this would be my best guess. i build this for a MsSql databse but you can adjust it for mySql in a few simple steps(First install mySQL connector).
I dont have a MsSQl database at my disposal atm so i didnt try it at home but it should work like this. Ofcourse edit the connection string so it fits your database
string fileName = "state_list.txt";
var lines = File.ReadLines(fileName);
Dictionary<string,string> splitted = new Dictionary<string,string>();
foreach (var line in lines)
{
string[] splitter = line.Split(',');
splitted.Add(splitter[0], splitter[1]); //Add eatch splitted line to dictionary so you can use key and value to insert into table
}
string connStr ="server = localhost; user = root; database = yourdb; port = 3306; password = xxxxxxxxx;"; // CREATE CONNECTION WITH YOUR DATABASE INFORMATION
SqlConnection conn = new SqlConnection(connStr);
try
{
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "INSERT INTO state_list(code,area) VALUES(#code, #area)";
foreach (KeyValuePair<string, string> pair in splitted)
{
comm.Parameters.Add("#code", pair.Key);
comm.Parameters.Add("#areas", pair.Value);
comm.ExecuteNonQuery(); // INSERT EACH PAIR INTO DATABASE
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close(); //CLOSE CONNECTION
(1)Parse the .txt file and (2)add the records to the DB. You can use entity framework, or any other ORM, or use ADO like #Jurriaan suggested.
If you are using Entity Framework, you can use this approach.
using(var context = new YourContext())
{
List<YourEntity> entities = new List<YourEntity>();
File.ReadAllLines("PathToFile")
.ToList()
.ForEach(s =>
{
string[] split = s.Split(',');
someList.Add(new YourEntity(split[0], split[1])); // Or set properties if not using a constructor.
});
context.YourTable.AddRange(entities);
context.SaveChanges();
}
One way I can think of is reading each line from text file using ReadLine(), and then use Split(',') on that line to get the abbreviation and name in a string array, and then you can easily add them to your database in a while loop.
Remove the ' from the file and then run below command.
Bulk Insert [dbo].[TableName]
From 'C:\FileName.csv'
with
(
FIELDTERMINATOR = ',', -- For Comma Seperated File
RowTerminator = '\n' -- RowTernimator i.e new Line
)
Did this a while back and added to blog at that time -- http://dotnetdevblog.blogspot.com/2007/10/bulk-inserting-from-csv-file-into.html

SELECT statement not returning anything

My issue is that the results are empty when executing the statement, even though when executing it in Microsoft's SQL server studio it works.
//This has two values in it (Ex: 4 and 2)
string[] arr2 = groupListValues.Split('-');
List<string> userID = new List<string>();
// Connect to the database
SqlConnection gconn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectinfohere"].ConnectionString);
gconn.Open();
SqlCommand command1 = new SqlCommand();
command1.Connection = gconn;
String sql = "SELECT ID FROM Users WHERE Group = #groupID";
command1.CommandText = sql;
command1.Parameters.Add(new SqlParameter("#groupID", ""));
SqlDataReader reader = command1.ExecuteReader();
//issue is in this loop
foreach (string str in arr2)
{
command1.Parameters["#groupID"].Value = str;
while (reader.Read())
{
userID.Add(reader["ID"].ToString());
}
}
Not sure what the issue is. The "ID" I'm getting in the SQL statement is of type bigint, could that cause an issue?
The reason I am setting the parameter inside the foreach loop is because, for each value in arr2 corresponds to a group that several users could be attached to. So I need to loop through that, get the users attached to each groupID, then add all their ID's to a list.
There are two problems with you code:
The first one is that you setting the #groupID parameter after you execute the reader. To fix it, execute the reader after you set the parameter value like this:
foreach (string str in arr2)
{
command1.Parameters["#groupID"].Value = str;
using(SqlDataReader reader = command1.ExecuteReader())
{
while (reader.Read())
{
userID.Add(reader["ID"].ToString());
}
}
}
The second problem is that Group is a reserved keyword in SQL, so you need to wrap it with square brackets like this:
String sql = "SELECT ID FROM Users WHERE [Group] = #groupID";

Add values to a table cell using C#

I want to add multiple values to a table cell separated by commas, the table I got is
Id ,Name , Type . I want to add multiple names in the name column, so the row will be something like:
ID Name Type
1 Peter, Jas , Roden , Karen Class A
I have done simple insertion which is:
[WebMethod]
public static string Insertion(string Name)
{
//List<string> result = new List<string>();
SqlConnection con = new SqlConnection("Data Source=XXX;Initial Catalog=XXX;User ID=sa;Password=XXXXX");
{
string query = "Insert into TestTable values #Name";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = Name;
{
con.Open();
cmd.ExecuteNonQuery();
//test();
con.Close();
return "True";
}
}
}
Can any one guide me on how to add multiple names which should be separated by commas, also I need to make sure there is no duplication of names.
you can send parameter value as "Peter, Jas , Roden , Karen" then it will insert that text in to given record.
but if you have array or List of names to be added, you can easily create the insert string as below
var names = string.Join("," ,namesArray.Distinct());
now you can call the service method using above generated names string
Can any one guide me on how to add multiple names which should be separated by commas
You need to use parameterized queries. It will also help you inb avoiding sql injection attacks.
like
cmd.Parameters.AddWithValue("#name",name);
also i need to make sure there is no duplication of names
Something like this should work for you
string name = "a,b,c,d,a,b,c,d";
HashSet<string> h = new HashSet<string>(name.Split(','));
string distinctNames = string.Join(",", h);

Deleting Multiple Rows from an Access Database

I want to delete multiple records from access database using array.
The array is loaded dynamically from file names.
Then i query the database, and see if the database column values are matching with the array values, if not then delete it, if matches then do not delete it.
the problem is that:
Following is the code that deletes all records irrespective of the where in Condition.
arrays = Directory.GetFiles(sdira, "*", SearchOption.AllDirectories).Select(x => Path.GetFileName(x)).ToArray();
fnames.AddRange(arrays);
here I have use also for loop but that also didnt help me out :( like for(int u = 0; u < arrays.length; u++) { oledbcommand sqlcmd = new oledbcommand ("delete from table1 where name not in ("'+arrays[u]+"')",sqlconnection);
I am using this one currently foreach(string name in arrays)
{
OleDbCommand sqlcmd = new OleDbCommand("delete from table1 where name not in ('" + name + "')", sqlconnection);
sqlcmd.ExecuteNonQuery(); }`
One problem is that your code is confusing.
string [] a = {"" 'a.jpg', 'b.jpg', 'c.jpg' "}
First, you have double " in the beginning,should only be one.
string [] a = {" 'a.jpg', 'b.jpg', 'c.jpg' "}
Then this created a string array with one element,
a[0] = "'a.jpg', 'b.jpg', 'c.jpg'";
Then you do a foreach on this which natuarly ony executes once resulting in this query:
delete from table1 where name not in ('a.jpg', 'b.jpg', 'c.jpg')
But when you load the array dynamically you probably get this array
a[0] = 'a.jpg';
a[1] = 'b.jpg';
a[1] = 'c.jpg';
which will execute 3 times in the foreach resulting in the following 3 queries
delete from table1 where name not in ('a.jpg')
delete from table1 where name not in ('b.jpg')
delete from table1 where name not in ('c.jpg')
After the second one the table will be empty.
You should try this instead:
string[] names = { "a.jpg", "b.jpg","c.jpg","j.jpg" };
string allNames = "'" + String.Join("','", names) + "'";
OleDbCommand sqlcmd = new OleDbCommand("delete from table1 where name not in (" + allNames + ")", sqlconnection);
sqlcmd.ExecuteNonQuery();
Where names is created dynamically ofcause and this will result in the following query matching your test:
delete from table1 where name not in ('a.jpg', 'b.jpg', 'c.jpg')
My preferred way to dynamically fill an array is to use a list instead as a pure array is fixed in size and any change needs to create a new array.
You can loop over a list as eacy as an array.
List<string> names = new List<string>();
//or user var keyword
var names = new List<string>();
Then just use add method to add elements, loop this as needed.
names.Add(filename);
Then for the concatenation:
string allNames = "'" + String.Join("','", names.ToArray()) + "'";
And you are done.
Or you could use
string[] filePaths = Directory.GetFiles(#"c:\MyDir\", "*.jpg");
string[] names = filePaths.ToList().ConvertAll(n => n.Substring(n.LastIndexOf(#"\") + 1)).ToArray();
posting my comment as a answer
your string is not reading in 4 entries, its reading one entry of
string names = " 'a.jpg', 'b.jpg','c.jpg','j.jpg' ";
it should be
string[] names = { "a.jpg", "b.jpg","c.jpg","j.jpg" };
before your for each had a count of 1 now it should have a count of 4 with the actual values
Edit:
Not a lot of effort in this solution i must admit but if you want dynamic input could do something like:
string name = " 'a.jpg', 'b.jpg','c.jpg','j.jpg' ";
string[] names = name.Split(',').Select(x => x.Trim(' ').Trim('\'')).ToArray();
will update later if i get the change as the trims are not good atm
For populating it, if you want it as enumerable a example could be something like
IEnumerable<string> filelocations = Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories).Select(x => Path.GetFileName(x));
or for string array
string [] lok = Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories).Select(x => Path.GetFileName(x)).ToArray();
Sounds like you're either not reading the file correctly or the file is empty. You should be checking the array to make sure it's not empty before running the operation against the database. If the array is empty, it SHOULD delete everything in the database as there are no matches.
You need to define the array like this:
string[] names = { "a.jpg", "b.jpg", "c.jpg", "j.jpg" };
the way you are defining the array it contains only one value:
" 'a.jpg', 'b.jpg','c.jpg','j.jpg' "
The code in your comment will delete any files not matching the first file. that would be all non 'a.jpg' files. The next iteration will delete all files that don't match 'b.jpg' which would be 'a.jpg'. This results in an empty table. Edit: The array declaration you have generates a good IN clause when you do it manually, but when you're getting a list of filenames, you're not generating this same string.
You need to perform a join on the array to generate a single string for your where clause that way the where clause includes all files. Your ultimate where clause should look like:
where name not in ('a.jpg','b.jpg','c.jpg','d.jpg')
Right now you have:
where name not in ('a.jpg')
... next iteration
where name not in ('b.jpg')
Also, be mindful that IN operations are expensive and the longer the array is the faster the query grows.
Try using a list if you don't want to create a static sized array
List<string> names = new List<string>();
names.Add("a.jpg");
names.Add("b.jpg");
names.Add("c.jpg");
foreach (string name in names)
{
OleDbCommand sqlcmd = new OleDbCommand("delete from table1
where name not in (" + name + ")",
sqlconnection);
sqlcmd.ExecuteNonQuery();
}

Categories