i'm stucked again. Is there any way to "connect" a graph from a form to a MYSQL database? I made the connections(forms-> database). I want that graph to automaticaly loads the columns, and the values from my database . Thanks a lot !
OK, I assume you want to show a Chart?
It is easy to use, just drop it on the form, define its series and load points.
Some or all of the Information you are looking for is in the metatables of each DBMS; in MYSQL these are in the various information_schema tables. Below is an example that loads all table names and the count of their columns into a chart named ch_tables, which contains one series called columns. It assumes you have an open Connectioncalled DBCand a Database provided in the parameter.
public void loadChart(string schema)
{
try
{
string allTables =
" SELECT table_name, count(COLUMN_NAME) "
+ " FROM information_schema.COLUMNS "
+ " where table_schema = '" + schema + "' group by table_name" ;
MySqlCommand cmd = new MySqlCommand(allTables, DBC);
MySqlDataReader rdr = cmd.ExecuteReader();
ch_tables.Series["columns"].Points.Clear();
while (rdr.Read())
{
ch_tables.Series["columns"].Points.AddXY(rdr[0], rdr[1]);
}
rdr.Close();
}
catch (MySqlException ex) { /* error handling */ }
}
I hope this gives you a start to expand it and to create other charts.
The information_schema tables contain a lot of intersting stuff; you can find the number of rows as TABLE_ROWS in information_schema.TABLES.
When asking a question it is always a good idea to give both us and yourself as much details as possible. Creating a dummy chart in Excel would have been a good idea to show just what you mean..
EDIT : I accidentally hard coded the schema name, even though the function was prepared to read of a dynamically choosen database..
Related
I am creating a footer of a receipt with Graphic.DrawString. The data is being SELECT from my database. Currently my table design holds 5 fields for the lines (line 1, 2, 3 up to 7). They are all single lines which is not very flexible. Say I want to put in a promo or a fairly long message on my footer. I am thinking of changing my table design to have 1 column of just the message and the data type probably text or varchar. What can I do to put multiple lines in that field?
EDIT: (Update: My receipt is created in Winform)
You should try this code.
private string GetDBString(string SqlFieldName, SqlDataReader Reader)
{
return Reader[SqlFieldName].Equals(DBNull.Value) ? String.Empty : Reader.GetString(SqlFieldName);
}
Then try something like this.
private void somemethod()
{
string query = "SELECT * FROM [mssql_table_name] WHERE id=1";
//I suppose you should have your datarow as id one. This helps a lot or where line="data in that"
//whatever helps to find your row
SqlConnection sqc = new SqlConnection(connection_string); // Defined by you
sqc.Open();
SqlCommand command = SqlCommand(query,sqc);
SqlDataReader reader = command.ExecuteReader();
this.footer.Text = GetDBString("line1", reader) + "\n" + GetDBString("line",reader)... etc;
All you need is before the new GetDBString insert between: + "\n " +
I hope I did help you and I understood your problem well.
This question is an extension to another I asked Here
I have a win form which has checkbox controls in it. The names of the checkboxes matches column names of a table. I can not normalize the tables cause of huge data involved, already received for the live project. so everything stays as it is.
I get the selected checbox names as a csv col1,col2,col3 which later i concatenate it to sql string.(no SPs as its a sql compact 3.5 sdf dbase).
In my GetData() method of the DataAccess class i form the sql string. But to avoid sql injections how can ensure that the column names passed are validated.
// Get Data
// selectedMPs: string csv, generated from the list of selected posts(checkboxes) from the UI, forming the col names in select
public static DataTable GetDataPostsCars(string selectedMPs, DateTime fromDateTime, DateTime toDateTime)
{
DataTable dt;
//string[] cols = selectedMPs.Split(','); //converts to array
//object[] cols2 = cols;//gets as object array
//=== using cols or cols 2 in String.Format does not help
// this WORKS, but as i am aware its prone to injections. so how can i validate the "selectedMPs" that those are columns from a list or dictionary or so on? i am not experienced with that.
string sql = string.Format(
"SELECT " + selectedMPs + " " +
"FROM GdRateFixedPosts " +
"WHERE MonitorDateTime BETWEEN '" + fromDateTime + "' AND '" + toDateTime +
using (cmd = new SqlCeCommand(sql,conn))
{
cmd.CommandType = CommandType.Text; //cmd.Parameters.Add("#toDateTime",DbType.DateTime);
dt = ExecuteSelectCommand(cmd);
}
return dt;
}
this WORKS, but as i am aware its prone to injections. so how can i validate the "selectedMPs" that those are columns from a list or dictionary or so on? i am not experienced with that. I would really appreciate your help. Thanks in advance.
This is the only possible approach, and there is no risk of injection with SQL Server Compact, as that database engine only executes a single statement per batch.
I am inserting new rows into a dataGridView Table. I have a sql sting that looks like this.
sql = #"INSERT INTO " + myNameRange + " VALUES ("+rowString+")";
My method that works looks like this.
public static void inSertRow(string myNameRange, string rowString)
{
string sql = null;
sql = #"INSERT INTO " + myNameRange + " VALUES ("+rowString+")";
if (myCommand == null)
{
MessageBox.Show("ERROR :: dfsdfsdf");
}
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
}
When I bring in "rowString" into the VALUES portion of the sql string, my question is;
Is there a way to set the "justification" / alignment of the information in that cell? Can it be done within the sql string?
So if my rowString of information coming in is ('city', 'state', 'zip') and I want city and state to be left aligned in the cell, but zip to be centered aligned.. can this be done?
Thanks
Formatting the way data looks is not the job of a database. When you insert your data you want to keep it a simple as possible. The time to format your data is when you read the data from the database.
You may want to justify your data centrally in one application but not in another. However the value stored in the database remains the same.
If you want to remove leading or trailing spaces use the ltrim and rtrim functions.
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?
protected void BtnSubmit_Click(object sender, EventArgs e)
{
string x = Request.QueryString["SubId"];
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
{
comCmd.ExecuteNonQuery();
}
}
}
An INSERT can't have a WHERE clause. It makes no sense to have one, you're putting data in, not narrowing it down.
If you're trying to change preexisting data, that's an UPDATE, not an INSERT. Here's an example:
"UPDATE Submission
SET Status='decline', StatusComment='" + TbComments.Text + "', StatusValue = 2
WHERE SubmissionId = " + x
That is incorrect INSERT syntax. Correct INSERT syntax is:
INSERT INTO tableName (columnList) VALUES (valueList)
columnList and valueList must have same count of items and values must be of type expected by columns.
or
INSERT INTO tableName (columnList)
SELECT columnList2
FROM tableName2
WHERE conditionsFromTable2
columnList and columnList2 must have same count of items of same types. You can use any complicated select joined over multiple tables with condition applied on data from these tables.
You need to use UPDATE, not INSERT
INSERT insert new row, therefore WHERE makes no sense
Where clause is not allowed in Insert query. Form your code I guess that you need to use Update query.
You'r trying to INSERT INTO Submission data from TbComments. So you need to SELECT the data from TbComments and then INSERT INTO Submission
string comQuery =
"INSERT INTO Submission (
Status,
StatusComment,
StatusValue)
SELECT
'decline',
TbComments.Text,
2)
FROM TbComments
WHERE SubmissionId =" + x;
So your SQL statement is:
"INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES (blah) WHERE SubmissionId =" + x;
The problem is definitely the WHERE. WHERE isn't valid for INSERT - See the MSDN documentation for the Insert command. Since you're filtering by SubmissionId, you probably want to do an UPDATE instead.
As for a better way of finding the problem, learning to use the MSDN documentation is a good step. A quick Google search for "msdn t-sql insert" will give you the page I linked to earlier in this answer. Documentation, experience, Google and Stack Overflow. That's how you find solutions :)
Ok, so here's the problem I have to solve. I need to write a method in C# that will modify a table in SQL Server 2008. The table could potentially contain millions of records. The modifications include altering the table by adding a new column and then calculating and setting the value of the new field for every row in the table.
Adding the column is not a problem. It's setting the values efficiently that is the issue. I don't want to read in the whole table into a DataTable and then update and commit for obvious reasons. I'm thinking that I would like to use a cursor to iterate over the rows in the table and update them one by one. I haven't done a whole lot of ADO.NET development, but it is my understanding that only read-only server side (firehose) cursors are supported.
So what is the correct way to go about doing something like this (preferably with some sample code in C#)? Stored procedures or other such modifications to the DB are not allowed.
jpgoody,
Here is an example to chew on using the NerdDinner database and some SQLConnection, SQLCommand, and SQLDataReader objects. It adds one day to each of the Event Dates in the Dinners table.
using System;
using System.Data.SqlClient;
namespace NerdDinner
{
public class Class1
{
public void Execute()
{
SqlConnection readerConnection = new SqlConnection(Properties.Settings.Default.ConnectionString);
readerConnection.Open();
SqlCommand cmd = new SqlCommand("SELECT DinnerID, EventDate FROM Dinners", readerConnection);
SqlDataReader reader = cmd.ExecuteReader();
SqlConnection writerConnection = new SqlConnection(Properties.Settings.Default.ConnectionString);
writerConnection.Open();
SqlCommand writerCommand = new SqlCommand("", writerConnection);
while (reader.Read())
{
int DinnerID = reader.GetInt32(0);
DateTime EventDate = reader.GetDateTime(1);
writerCommand.CommandText = "UPDATE Dinners SET EventDate = '" + EventDate.AddDays(1).ToString() + "' WHERE DinnerID = " + DinnerID.ToString();
writerCommand.ExecuteNonQuery();
}
}
}
}
Your problem looks like something that you should be solving using T-SQL and not C#, unless there is some business rule that you are picking up dynamically and calculating the column values T-SQL should be the way to go. Just write a stored procedure or just open up Management studio and write the code to make your changes.
If this does not help then please elaborate on what exactly you want to do to the table, then we can help you figure out if this can be done via T-SQL or not.
[EDIT] you can do something like this
string sql = " USE " + paramDbName;
sql+= " ALTER TABLE XYZ ADD COLUMN " + param1 + " datatype etc, then put semicolon to separate the commands as well"
sql+= " UPDATE XYZ SET Columnx = " + some logic here
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
get this executed on the required instance of Sql Server 2008.
If you have too many lines of text then use StringBuilder.
Here's a suggestion:
You can read data using a DataReader , create a update command for current row and add it to a list of commands.Then run update commands in a transaction.
something like this:
var commands=new List<SqlCommand>();
while(dr.Read())
{
var cmd=new SqlCommand();
cmd.CommandText="Add your command text here";
commands.Add(cmd);
}
using(var cnn=new SqlConnection("Connection String"))
{
IDbTransaction transaction;
try
{
cnn.Open();
transaction=cnn.BeginTransaction();
foreach(var cmd in commands)
{
cmd.Transaction=transaction;
cmd.ExecuteNonQuery();
cmd.Dispose();
}
transaction.Commit();
}
catch(SqlException)
{
if(transaction!=null)
transaction.Rollback();
throw;
}
}