Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to retrieve something from a database in vb.net and display it. It has 4 columns with unlimited amounts of rows, could be 5, could be 10.
First column is an int, second a name, 3rd date and 4th a date. I have to sort it by date. What would be the best way to retrieve all the data and store it?
One solution I thought of was to store each individual column into an array then sort them, but I am not sure how to sort more than 2 arrays. The next solution I though of was to use a datatable and organizing the columns but I am just not sure how to do.
Any ideas?
store the data in a Table inside of a dataset. If you do this then you can select all of the SQL information at once, throw it into the dataset's table and then display it in something like a datagrid.
Be sure to include for SQL:
Imports System.Data.SqlClient
Dim conn As New SqlConnection
conn.ConnectionString = "YOUR CONNECTION INFORMATION"
Dim sQuery As String = "SELECT [Number], [Name], [Date], [Date2] " & _
"FROM [YourTableName] " & _
"ORDER BY [Date]"
Dim da As New SqlDataAdapter(sQuery, conn)
Dim ds As New DataSet
Dim dt As New DataTable()
da.Fill(ds, sQuery)
dt = ds.Tables(0)
dgvYourDataGridView.DataSource = ds
dgvYourDataGridView.Refresh()
conn.Close()
conn.Dispose()
Not sure if that's what you're looking for or not.
Related
I'm still somewhat new to ASP.NET and VB, and I found out that it's vastly different from the ASP I learned where I used Recordset to extract data from the database. Can someone give me some pointers on how to extract data from a database? Here is what I used to at least connect:
Dim conn As OdbcConnection
conn = New OdbcConnection("DSN=southwind")
Dim mystring as String = "SELECT GroupName FROM Group"
Dim cmd As OdbcCommand = New OdbcCommand(mystring, conn)
conn.Open()
Dim reader As OdbcDataReader = cmd.ExecuteReader()
The last line gives me an error saying:
Exception Details: System.Data.Odbc.OdbcException: ERROR [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near the keyword 'Group'.
But since I don't quite understand ASP.NET completely, not too sure what it means even though the syntax looks fine. Removing that line runs the code just fine. How would I display all the contents from the GroupName column in table Group?
EDIT: Thanks everyone, I completely forgot that Group was reserved in SQL.
Group is a keyword in SQL, you need to wrap it in square brackets like this,
SELECT GroupName FROM [Group]
This would assume the Group to be a name of the table, instead of a key word; of GROUP BY clause.
Group is a keyword in SQL. If your table name or column names referenced in your query are keywords, you can enclose them in brackets.
Dim mystring as String = "SELECT GroupName FROM [Group]"
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a asp.net application, which save some users data using post form. For that I have a simple query listed below.
"UPDATE myTable SET LastUpdatedOn='"
+ DateTime.UtcNow + "', Completed='1'
WHERE ID='" + requestid + "'"
This fails some times. But I think there are no issue with it. So please let me know why it happens.
You should familiarize yourself with parameterized queries, and start using them to protect your system from SQL Injection attacks.
using (var cmd = conn.CreateCommand()) {
cmd.CommandText =
"UPDATE myTable SET LastUpdatedOn=#Time, Completed='1' WHERE ID=#Id";
cmd.Parameters.AddWithValue("#Time", DateTime.UtcNow);
cmd.Parameters.AddWithValue("#Id", requestid);
var count = cmd.ExecuteNonQuery();
if (count != 1) {
Console.Error.WriteLine(
"Warning: Cannot update myTable for ID {0}", requestid
);
}
}
As an added benefit, this approach eliminates all possible data formatting issues, and speeds up your queries by letting SQL Server cache query plans. But the main benefit is thwarting the attempts of "Bobby Tables" of the world to gain unauthorized access to your system.
DateTime.UtcNow is not likely parseable to a datetime for the query. Try:
DateTime.UtcNow.ToString('yyyy-MM-dd hh:mm:ss')
(also, I may have screwed up my "m's", so double check it)
I'm not exactly sure why this would break. We would need to see the schema of the table to get a better idea of what could be going wrong. On another note, I would suggest that you use parameterized queries instead of simply concatenating your query. Your current query could be vulnerable to SQL injection depending on where the inputs come from. Try changing your code to something like this to see if it alleviates the error (this will also mitigate the SQL injection risk):
SqlCommand cmd = new SqlCommand("UPDATE myTable SET LastUpdatedOn = #LastUpdatedOn, Completed = #Completed WHERE ID = #RequestId", sqlConnectionObject);
cmd.Parameters.AddWithValue("#LastUpdatedOn", DateTime.UtcNow);
cmd.Parameters.AddWithValue("#Completed", 1);
cmd.Parameters.AddWithValue("#RequestId", requestid);
cmd.ExecuteNonQuery();
insted of using DateTime.UtcNow consider to use getdate() if Sql Sevrer or simmilar function in whatever database you are using
"UPDATE myTable SET LastUpdatedOn= getdate(), Completed='1' WHERE ID='" + requestid + "'"
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
Does anyone know of a script to download email from Gmail and store it to a SQL server? (for backup purposes)
I am looking for a .NET solution (C#).
EML files are plain text.
Simply create a table in your database with one column (and all the others you need, that's for you to decide) of type nvarchar(max) that will store the contents of the email file. For example call this column email_content
Then do something like this:
string email = File.ReadAllText("Path/to/EML/File");
And then do something like:
using (SqlConnection con = new SqlConnection("YourConnectionStringHere"))
{
con.Open();
using(SqlCommand command = new SqlCommand("INSERT INTO your_table (email_content) values (#email_content)",con)
{
command.Parameters.AddWithValue("#email_content",email);
command.ExecuteNonQuery();
}
}
*That's assuming you are using SQL Server but the principle is the same for any other database.
Sometimes when I insert a new row to a table in my database, it comes before the last row.
I will explain. If I have the following table:
ID Name
1 James
2 Terry
3. Miriam
4. Arthur
and I want to insert a new row with "Danny", sometimes this happens:
ID Name
1 James
2 Terry
3. Miriam
5. Danny
4. Arthur
My code works in 99 percent of the cases, but sometimes it just happens.
I do not know what to do? Is this normal?
I work with ASP.NET, VB.NET, .NET 3.5 and MySQL database with autoIncrement on the ID column.
I've seen it also happen in Access and SQL Server.
This is my code:
' insert to user_table
Dim connString As String = ConfigurationManager.ConnectionStrings("mysql_ConnString").ConnectionString
Dim conn As MySqlConnection = New MySqlConnection(connString)
Dim sqlCommand As String
sqlCommand = "INSERT INTO user_table (Nickname,Email,Pass,SubscriptionMode,SignupDate,LastVisitDate,VisitCounter) VALUES (#Nickname,#Email,#Pass,#SubscriptionMode,#SignupDate,#LastVisitDate,#VisitCounter)"
Dim cmd As New MySqlCommand(sqlCommand, conn)
Try
conn.Open()
cmd.Parameters.AddWithValue("#Nickname", txtNickname.Text)
cmd.Parameters.AddWithValue("#Email", txtEmail.Text)
cmd.Parameters.AddWithValue("#Pass", password)
cmd.Parameters.AddWithValue("#SubscriptionMode", 1)
cmd.Parameters.AddWithValue("#SignupDate", Date.Now)
cmd.Parameters.AddWithValue("#LastVisitDate", Date.Now)
cmd.Parameters.AddWithValue("#VisitCounter", 0)
cmd.ExecuteNonQuery()
Catch ex As Exception
GlobalFunction.sendToLog(ex, "problem in create profile page - sub: insertUser_table")
GlobalFunction.jsMessage(Me, "problem in create profile page - sub: insertUser_table")
Return False
Finally
conn.Close()
End Try
In general, when you do
select * from Users
you cannot rely on the order of records. if you need your records in some particular order, you'll have to explicitly specify an order by clause
select * from Users order by ID
MySql is a Relational Database Management System which means that it is based on the relational model. The physical order of the rows of a table (which represents a relation) is of no importance. You must think of tables as Unorder Sets. If you want to present your data in a specific order you must use the order by clause.
I think that if you use InnoDB you can use a clustered index to specify the order of the rows.
To correct your question: My database table is not ordered
Your database table is ordered, but your select statement is not ordered.
And because it is not that's why you're not getting an ordered result.
The result that you are getting is in undefined order!
If you want an ordered result you must always specify and order by clause in your query.
Make ID your primary key and make it indexed. No matter what your newly entered row will be the last one. For selecting use the suggestions above about order by.
As Bala R said, you can't have SQL determine how you want to organize your data, so you want to do something like this:
SELECT * FROM Users ORDER BY id ASC
ex: (1,2,3,4,5)
Or this:
SELECT * FROM Users ORDER BY id DESC
ex: (5,4,3,2,1)
This is a really odd situation that I can't seem to work out where the problem lies.
I have a simple ASP textbox and button, on clicking the button I have a simple sqlconnection/command routine perform a simple update to a database based on the text value of the textbox.
Code:
Using myConnection As SqlConnection = New sqlConnection(ConfigurationManager.ConnectionStrings("sqldbconn").ConnectionString)
myConnection.Open()
Dim strSQL As String = "insert into users(name) select #name"
Dim myCommand As New Data.SqlClient.SqlCommand(strSQL, myConnection)
myCommand.CommandType = Data.CommandType.Text
myCommand.Parameters.Add(create_Parameter("#name", Data.SqlDbType.VarChar, 50, Data.ParameterDirection.Input, txName.Text))
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
create_Parameter is just a simple tested function which performs the 2-3 lines it normally takes to create a parameter object.
The problem I have, is that the value added to the database is always a comma, followed by the text given in the textbox.
I have performed response.write's prior to the ExecuteNonQuery call to check both the Parameter value and the CommandText, which are fine and as expected. If I copy what's expected into a management studio query window, it works fine.. users is a simple table with varchar column, no triggers or constraints etc. There are no other sub's in the ASP code other than what I've shown.
So now I'm stuck, what else can I do to work out where/why this comma is being added to my insert statement???
Cheers!
Probably nothing to do with your issue, but I wold normally write an insert like this:
INSERT INTO users (name)
VALUES #name