How to display random 10 record from database? - c#

How to randomly display 10 question from database? How can i check the answer is correct with database or not?
db.command(true, "SELECT * FROM question WHERE Age_group='" +category + "'");
foreach (DataRow item in db.result.Rows)
{
question_list.Add (Convert.ToInt32(item["id"]));
}
for (int i = 0; i < max_question; i++)
{
int index = ran.Next(question_list.Count);
question_choose.Add(question_list[index]);
question_list.Remove(question_list[index]);
}

select top 10 * from table order by newid()
also, see "order by newid()" - how does it work?

Related

Create generic SQL INSERT statement from datatable with looping

I'm trying to create a generic method of taking a datatable and creating a SQL INSERT statement from its contents.
I've spent the better part of a couple of days researching this on StackOverflow.
I just need some help with the looping section code--it doesn't give the desired results and I've reached the limit of my coding skills.
I don't need BulkCopy solutions or database specific ones. I just need the INSERT string. I don't care about SQL injections or anything else. This is an internal legacy app that needs to have a few repetitive/manual processes automated.
I have written an example console program to demonstrate. The size of the datatable isn't really a factor form me. It is never over 60 rows and has 6 columns:
The datatable should look like:
ID Group X Y Z
1 A 100 200 400
2 B 200 400 800
3 C 300 600 1200
4 D 400 800 1600
5 E 500 1000 2000
The example console app is:
using System;
using System.Data;
namespace crSQLInsert
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("ID");
dt.Columns.Add("Group");
dt.Columns.Add("X");
dt.Columns.Add("Y");
dt.Columns.Add("Z");
for (int i = 0; i < 5; i++)
{
Random rnd = new Random();
char cLtr = Convert.ToChar(i+65);
double colVal = ((i + 1) * 100) ;
DataRow dr = dt.NewRow();
dr["ID"] = 1 + i;
dr["Group"] = cLtr;
dr["X"] = colVal ;
dr["Y"] = colVal * 2;
dr["Z"] = colVal * 4;
dt.Rows.Add(dr);
}
createSQL(dt);
}
public static void createSQL(DataTable dtSQL)
{
// Create generic SQL query to add datatable contents to my_table
string sSQL = "";
sSQL += "INSERT INTO my_table (ID, Group, X, Y, Z) VALUES (";
for (int i = 0; i < dtSQL.Rows.Count; i++)
{
for (int j = 0; j < dtSQL.Columns.Count; j++)
{
sSQL += dtSQL.Rows[i][j].ToString().Trim();
if (j != dtSQL.Columns.Count - 1)
{
sSQL += "','";
}
else
{
sSQL += "')";
}
}
}
Console.WriteLine(sSQL);
}
}
}
The resulting SQL string should be like below:
(I've formatted it so that it's easier to read--the actual string doesn't necessarily need the \r\n as it will end up as a string in an ODBCCommand().
INSERT INTO my_table (ID, Group, X, Y, Z)
VALUES (1','A','100','200','400'),
(2','B','200','400','800'),
(3','C','300','600','1200'),
(4','D','400','800','1600'),
(5','E','500','1000','2000');
Thanks for any help.

How can i insert datatable rows in another datatable at a specified index?

I have two data tables with auto generated columns and info from two different Access databases.
The names are:
Export data table (source)
School data table (target)
I want to select the information that the export database has beginning from column 19 (assuming 0=index) and insert that information in the school data table beginning from column 203 (assuming 0-index)
i already tried this method:
try
{
cb = new OleDbCommandBuilder(dataAdapterSchool);
cb.GetUpdateCommand();
cb.GetInsertCommand();
cb.GetDeleteCommand();
for (int i = 0; i <= 19; i++)
{
DataRow newRow = schoolDb.NewRow();
newRow[i + 19] = exportDb.Columns[202 + i];
}
Grid.ItemsSource = schoolDb.DefaultView;
dataAdapterSchool.Update(schoolDb);
testbox.Text = cb.GetUpdateCommand().CommandText;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The problem here is that it gives me the error:
Unable to cast object of type 'System.Data.DataColumn' to type 'System.IConvertible'
Which is (according to google) the error that occurs when you don't specify the column names that the source should insert to. Since there are many columns, I want to find a way to do this without specifying the column names.
Any help would be appreciated,
There's an mistake in your code:
for (int i = 0; i <= 19; i++)
{
DataRow newRow = schoolDb.NewRow();
newRow[i + 19] = exportDb.Columns[202 + i]
}
you need to iterate over rows and replace exportDb.Columns[202 + i] for exportDb.Rows[x][202 + i]

How to split DataTable if columns are greater than 1024?

I have Data table having 3k and more columns , as we all know that SQL Tables does not support more than 1024 Columns .I will be having this another table for it .
I just need to split DataTable if columns are greater than 1024.
I need an efficient way.
Thanks in advance.
I have never seen database table with such a big number of columns.
I do not know, how many rows does your DataTable typically have. You could transpose DataTable or below is a code snippet how to split DataTable. I used #jdweng idea with copy table with al values and then delete unwanted columns backwards. I cannot assess if this is the most efficient way. I did not test it on DataTable with rows.
static List<DataTable> SplitTables(DataTable largeTable)
{
var tables = new List<DataTable>();
int chunkSize = 1024;
int cycles = largeTable.Columns.Count / chunkSize;
for (int i = 0; i <= cycles; i++)
{
var tempTable = largeTable.Copy();
for (int j = largeTable.Columns.Count - 1; j >= 0; j--)
{
if (!(j >= i * chunkSize && j < (i + 1) * chunkSize))
{
tempTable.Columns.RemoveAt(j);
}
}
tables.Add(tempTable);
}
return tables;
}
Read about normalization, as typically properly normalized database does not require tables with 1024+ columns. If will not help, you question can be solved by e.g.
1) count number of columns
SELECT count(*)
FROM information_schema.columns c
JOIN information_schema.tables t ON c.TABLE_NAME = t.TABLE_NAME
AND c.table_schema = t.table_schema
WHERE table_type = 'base table'
and c.table_name ='table_name_here'
2) if more than expected - create a new table
CREATE TABLE new_table_name_here
(...)

Sort C# ListBox Items

I'm using C# Adapter method, I add elements to a list and after that I call that list to fill a listbox, here is my button for do that:
private void button1_Click(object sender, EventArgs e) {
listCustomers.Items.Clear();
List < Customer > customers = CustomerList.GetCustomers();
List < CustomerSaldo > customersSaldo = CustomerListSaldo.GetCustomers();
int total = 0;
int totalCustomer = 0;
foreach(Customer customer in customers)
total++;
listCustomers.Items.Clear();
totalCustomer = total;
int x = totalCustomer;
foreach(CustomerSaldo customer2 in customersSaldo) {
if (x >= 1) {
listCustomers.Items.Add("Costumer ID # " + x + " is: " + customer2.Saldo);
x--;
}
}
}
This is what I get, it's ok but I want to know if exists a way to do this like this example:
Costumer #1 Saldo...
Costumer #2 Saldo...
Costumer #3 Saldo...
If you see my code I have a variable x, this variable is the total number of costumers, so I think that my sort has to start with this variable, but I don't know exactly how to do it, what can I do?
Reverse the list and start counting untill you reach the end:
//Reverse the list
customersSaldo.Reverse();
//Add new items
for(int i = 0; i < customers.Count; i++)
listCustomers.Items.Add(string.Format("Costumer ID # {0} is: {1}", (i+1).ToString(), customersSaldo[i].Saldo);
you can probably reverse (Using the Reverse method) your list "customersSaldo" before adding it, and then use the variable 'x' in increment order.
https://msdn.microsoft.com/en-us/library/b0axc2h2(v=vs.110).aspx

Populate an array element with 2 datarows at a time

i want to populate an array element with 2 datarows at a time.
i am using javascript pausescroller and on every single array element i want to show 2 Rows in the scroller.
sample code is
Datatable tblNews;
for(int i = 0; i < tblNew.Rows.Count; i++)
{
array[i] = tblNews.Rows[i][""].ToString() + "" + tblNews.Rows[i + 1][""].ToString();
}
but problem is i am getting error that no row found at position 1;
Any solution guys
Yah, quite simply, when you're getting to the end of your tblNew.Rows.Count you're adding another one and that doesn't exist in your rows...
so a quick and dirty fix...
for(int i = 0; i < tblNew.Rows.Count-1; i++)
{
// do a quick check to make sure there is a row there to get data from
string addMe = i + 1 <= tblNews.Rows.Count-1 ? tblNews.Rows[i+1][""].ToString() : "";
array[i] = tblNews.Rows[i][""].ToString() + "" + addMe;
}

Categories