I wonder why my SQL Server Express database table doesn't get updated when the method below executes successfully?
public void addUser(User user)
{
string query = "INSERT INTO users (username, password, firstname, lastname, isactive, accesslevel) VALUES (#usr, #psw, #fname, #lname, #status, #access)";
pSqlConn = new SqlConnection(pConnectingString);
SqlCommand cmd = new SqlCommand(query, pSqlConn);
SqlParameter pmtrUsername = new SqlParameter("#usr", user.Username);
SqlParameter pmtrPassword = new SqlParameter("#psw", user.Password);
SqlParameter pmtrFirstname = new SqlParameter("#fname", user.Firstname);
SqlParameter pmtrLastname = new SqlParameter("#lname", user.Lastname);
SqlParameter pmtrStatus = new SqlParameter("#status", user.IsActive);
SqlParameter pmtrAccessLevel = new SqlParameter("#access", user.AccessLevel);
cmd.Parameters.Add(pmtrFirstname);
cmd.Parameters.Add(pmtrLastname);
cmd.Parameters.Add(pmtrUsername);
cmd.Parameters.Add(pmtrPassword);
cmd.Parameters.Add(pmtrStatus);
cmd.Parameters.Add(pmtrAccessLevel);
pSqlConn.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Success!");
pSqlConn.Close();
}
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. StoreManagerDB)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=StoreManagerDB;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
Make sure the database connection variable is the right syntax and i advise you include an error syntax to show when the db is not connected
Related
I don't get it why my (very simple) code is working properly on my local machine from Visual Studio 2022 and on the local IIS 10 to connect to a sql server express (15) and on my webserver it's not. I'm sure that's a really simple quesion for you.
What I'm tryin' to do is a simple login page. My code in the Login.aspx is:
using System.Data;
using System.Data.SqlClient;
try
{
SqlConnection con = new SqlConnection(#"Data Source=BERLIN\SQLEXPRESS;Initial Catalog=membersarea; User ID=sa;Password=Test2022!");
SqlCommand sqlCmd = new SqlCommand("select * from useraccount where username=#userName and passWord=#Password", con);
sqlCmd.Parameters.AddWithValue("#userName", tbxUsername.Text.ToString());
sqlCmd.Parameters.AddWithValue("#passWord", tbxPassword.Text.ToString());
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCmd);
DataTable datatable = new DataTable();
sqlAdapter.Fill(datatable);
con.Open();
int i = sqlCmd.ExecuteNonQuery();
con.Close();
if (datatable.Rows.Count > 0)
{
Session["userName"] = tbxUsername.Text.ToString();
datatable.Dispose();
Response.Redirect("Content.aspx");
}
else
{
lblMessage.Text = "Benutzername oder Passwort falsch.";
lblMessage.ForeColor = System.Drawing.Color.DarkOrange;
lblMessage.Visible = true;
}
}
catch(Exception ex)
{
}
(I know that I'm not supposed to do this with the sa account, just to keep it simple... The only thing I do on the web server is to change the name of the sql server instance. Management Studio works fine with this User Id and Password on my web server. I installed the sql server using Plesk and I don't think it is working properly within plesk. Using the Management Studio I can restore backups, queries, create new accounts, etc.)
My Content.asps says Hi (including my name) and shows the Logout-Button. If you enter credentials that are not correct it says so and if you try to go to the content-Page without loggin' in you're redirected to the Login-page. That is what I want. Trouble is, it's not workin' on my webserver. It is simply doin' nothing. No error message, or something else. It takes a while, password is cleared again and username is still there. (Doesn't matter which credentials are used.)
I don't think that it comes to the first line of my code, and I don't know why. Are there DLLs that are needed, or what else did I forget? I'm pretty sure this is a absolute beginner problem but I can't figure it out.
Tried to fill in some code to alter the lblMessage, to find out where the problem starts, but nothing of it is displayed.
I think the trouble started when I checked the pattern web forms while creating the project. In the bin folder there is a "name-of-my-project".dll and a "name-of-my-project".pdb file. Those two are generated if you recreate your project. I'm pretty sure you guys know that - I did not. Or better I do know that they were generated, but not that they are necessary. (As I wrote before, I'm at the very beginning.)
In guess that in this *.pdb and/or *.dll the connection string is stored, too. When I recreate my project with the valid connection string for the web server and upload them, too - everything works as expected. Thank you, guys for your ideas.
I'm new to coding. I'm attempting to access a SQL Server file through WPF / C# and I am having trouble getting in the correct string, I believe. I do not yet fully understand SQL logins, but here is the code I have now, which I believe as close to correct as I can get on my own:
string CS = #"Data Source=(LocalDB)\v11.0; Integrated Security=true; AttachDbFileName=C:\Users\Madison\source\repos\TheRealStudyBot\TheRealStudyBot\TestingData.mdf";
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand("CREATE TABLE table1 (PK int, Name nvarchar(255), PRIMARY KEY *PK),);", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
con.Close();
This code is under public MainWindow(), after InitializeComponent(). The file path should be correct. The database is empty. I get this exception:
Win32Exception: Unknown error (0x89c50118)
Ran it once more and I think I may have accidentally altered my debug settings because now it also provides a window stating
The solution does not contain the specified document
(along with plenty of other jargony-code-exception-results-text). I don't see where I'm going wrong. Please help!
If you are on Visual Studio 2019,
Double Click on your LocalDB which opens Server Explorer
Clicking on your database, On the properties tab shows the connection string.
Copy that & Paste on CS!
And the Normal Connection String Format For LocalDB is,
Data Source=Your_DataSource;Initial Catalog=YourDatabaseName;Integrated Security=True;Pooling=False
I am developing a web site, it uses SQL Server 2008 R2 Express for its database. And in testing, there is a lot of data and images stored into this database.
According to wiki, the SQL Server Express edition has a 10 GB size limit. When I insert data and reach the limit, what exception will be thrown? Or, how do I detect the approaching limit problem by codes ?
I use EF 5 with code-first approach to insert large data set.
In tests I have seen that:
sp_spaceused
won't work as expected, it showed 12GB after deleting lots of records. And the other answers regarding query sys.databases were not clear enough to me.
Searching around I found a very good explanation regarding SQL Server 2012 Express Edition 10GB Size Limit on Ramons weblog [EDIT2018 updated link]
SELECT
[name] AS [Filename],
[size]/128.0 AS [Filesize],
CAST(FILEPROPERTY([name],'SpaceUsed') AS int)/128.0 AS [UsedSpaceInMB],
[size]/128.0 - CAST(FILEPROPERTY([name],'SpaceUsed') AS int)/128.0 AS [AvailableSpaceInMB],
[physical_name] AS [Path]
FROM sys.database_files
"... space includes the transaction log and it also includes all unused space within these files. .... SQL Server Express will start complaining when it cannot reserve any more space for the datafile."
So checking
CAST(FILEPROPERTY([name],'SpaceUsed') AS int)/128.0 AS [UsedSpaceInMB]
seems to be the best option.
In combination with EF in c# my request to the DB looks like
string sqlSelect = "SELECT CAST(FILEPROPERTY([name],'SpaceUsed') AS int)/128.0 AS [UsedSpaceInMB] FROM sys.database_files";
var dbResult = dbInstance.Database.SqlQuery<Decimal>(sqlSelect).FirstOrDefault();
double spaceUsedInGb = Convert.ToDouble(dbResult)/1024;
Execute this SQL command, and it will reveal the disk-space usage of current database.
sp_spaceused
It also can be used to query the space usage of specific table. This link provides useful information about this problem.
To check the database size query:
sys.databases
Just query this, perhaps with C# or if you use SSMS (sql server management studio) shell, you can schedule a job that emails you or whatever you want.
Example:
SQL Server 2008: How to query all databases sizes?
Edit: NOT sure if error is thrown, it should log to event log or a sql log...
Side note:
Developer version is only $50 and holds same as Datacenter which hold 524 PB
http://technet.microsoft.com/en-us/library/cc645993%28v=sql.105%29.aspx
To Check the Size of the Database Two Ways:
/* new school way - data plus log and run in the local db that you want to see
here you can see the log and the mdf file.
*/
SELECT size*8.0/1024.0 as size_in_gb, *
FROM sys.database_files
GO
/* old school way, run for all db size*/
sp_helpdb
FYI - the MDF and NDF files are the only ones that attribute to the file size exceeding 10GB.
I am using the following method to calculate database current size crucial for comparing with sql size limitations:
public static int GetDbSizeInMB([NotNull] string connectionString) {
using (SqlConnection sqlConnection = new SqlConnection(connectionString)) {
sqlConnection.Open();
using (var sqlCommand = new SqlCommand()) {
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = #"
SELECT SUM(CAST(FILEPROPERTY([name],'SpaceUsed') AS int)/128.0) AS [UsedSpaceInMB]
FROM sys.database_files
WHERE type_desc like 'ROWS' or type_desc like 'FULLTEXT'
";
sqlCommand.Connection = sqlConnection;
return Convert.ToInt32(sqlCommand.ExecuteScalar());
}
}
)
I'm using Visual Studio 2010 to build an ASP.NET web application, I'm working on dynamically populating (part) of the site map from information in a database. Right now I just have a dummy table in my App_Data folder, called DrugTest.mdf. The table is just called DrugTest1, which only has one field, DrugName. Where I'm hitting a wall is actually getting the data out of that table. Part of what I'm confused about is the connection string. I've looked at a lot of different information about connection strings, most notably http://www.connectionstrings.com/ but I'm a little confused as to how to actually apply said information to this project.
EDIT: I'm using SQL Server 2008 RC.
For example: Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Password and User Id are pretty self-explanatory, but as far as I know I didn't get either one of those, I just added a table to the App_Data folder and filled it with dummy data. ServerAddress is a little confusing, because this information isn't really stored on a server, it's just stored locally. And I'm honestly not sure what Initial Catalog means.
Here's the code to populate the sub-tree. You'll notice the connection string is left blank.
string connString = ""; // get the connection string
string commandString = "SELECT drugName FROM DrugTable1";
SqlConnection connection = new SqlConnection(connString); // connect to db
SqlCommand command = new SqlCommand(commandString, connection); // set up the command
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet drugs = new DataSet();
adapter.Fill(drugs);
foreach (DataRow row in drugs.Tables[0].Rows)
{
string drugName = row["Name"] + "";
SiteMapNode node = new SiteMapNode(this, drugName,
"~/PlaceHolderUrl?path=" + drugName,
drugName);
AddNode(node, root);
}
Furthermore, I've got a nagging suspicion that I'm not going about this the right way. I think this will be the proper implementation once the database is up and running, but for right now I just want to get it working so it's ready to go - just slap in the proper connection string and table/field names.
So, finally, my question(s): How would I go about connecting to this local table? What format should my connection string be? I noticed there's a lot of them. Is there a better way to do this/am I doing this wrong?
Another way of getting the right connection string check this out in the ServerExplorer window
On the Menu click on View->Server Explorer
In the Server Explorer window locate DrugTest.mdf
Right click the file and select Properties
You can see the right connection string in the properties
Copy the connection string and use
Note: that the file location was hard-coded. You might need to use |DataDirectory| later
Try replacing the Initial Catalog portion of your connection string with AttachDbFilename=|DataDirectory|DrugTest.mdf.
Also, if you're using SQL Server Express, you might need to include the instance in the Data Source, so might try Data Source=mySeverAddress\SQLExpress, where SQLExpress is the instance name.
BTW, at the http://www.connectionstrings.com site, you can find this information in the SQL Server 2008 page if you scroll down a bit to the section titled "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance."
I'm new to databases and am trying to add a new record using SQL. The code runs fine the first time, but the second time throws an error saying that it can't write duplicates to a unique key. The third time runs fine, but the fourth time throws the error. Basically, it seems that every other time, the error is thrown. I understand why the error would be thrown if data was written, but when I examine the database, it remains empty. What am I doing wrong in my code that is causing the query to not bother writing the data?
EDIT If I enter the SQL directly within the database, it works. It doesn't work when I use the C# code below.
using (SqlCeConnection con = new SqlCeConnection(conString))
{
con.Open();
using (SqlCeCommand com = new SqlCeCommand("INSERT INTO User (Name, Age, URL) VALUES ( #name, #age, #url )", con))
{
com.Parameters.AddWithValue("#name", "James Y");
com.Parameters.AddWithValue("#age", 28);
com.Parameters.AddWithValue("#url", "www.example.com" );
com.ExecuteNonQuery();
}
}
I've partially figured it out. Apparently you have to also download SQL CE Tools for Visual Studio. I did this and I had a new option to include SQL CE 4 into my project (I was using the SQLCE option, assuming that it would use 4.0 by default since that's the one I installed). Only problem now is that when I try and add it, it says that it's not supported by the project type (Console project). I saw a post on MSDN that said that SQLCE 4 was for web-only projects but it was a post from a few months back and the current download page says it's for web or desktop applications. Either way, this is proving to be too much of a hassle to bother with and so I'm just going to look for an alternate database if I can't resolve this soon.
FIXED I uninstalled SQLCE4 and the SQLCE Tools, then reinstalled them.
Try and do the following as your SQL:
INSERT INTO [User] (Name, Age, URL) VALUES ( #name, #age, #url )
User is a reserved word in sql server. You should try not to name your table as "user".
Name is a reserved word. Wrap it in []
using (SqlCeCommand com = new SqlCeCommand("INSERT INTO User ([Name], Age, URL) VALUES ( #name, #age, #url )", con))
Since you use DataDirectory in your connection string, the file is copied to your bin/debug folder, so you have several copies of the database, one in your project and one in your debug folder. Make the connection string a full path to avoid any confusion while debugging!