So I am using a Local Database (.mdf) in Visual Studio 2015. I had a hard time connecting to the database at first but now it is connecting as far as I can tell. I am using INSERT to add data to the database and I also have a variable telling me if any rows were affected once the user clicks the 'save' button but every time it says successful and I check the database and there is nothing there.
I have searched Google a bunch of times about this answer and everyone is saying to use SQL Server Management Studio to create the database and give the database a logical name. I did do that, but when I try to add that database to visual studio it says it gives me an error code 40; and i even detached the database from the server and tried adding just the database and it says that it does not have the correct permissions for it. So I do not know what to do!!
Here is what I got so far and hopefully I can get some help!
Lets start off with the database:
Database name: dbo.WebLogins
[Id] INT IDENTITY (1,1) NOT NULL,
[Nickname] VARCHAR (50) NULL,
[WebsiteURL] VARCHAR (200) NULL,
[WebsiteUsername] VARCHAR (50) NULL,
[WebsitePassword] VARCHAR (50) NULL,
[WebsiteEmail] VARCHAR (50) NULL,
[WebsiteAbout] VARCHAR (200) NULL,
[WebsiteRating] INT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
Now I have some textboxes and a trackbar and two buttons:
txtNickname
txtURL
txtUsername
txtEmail
txtPassword
txtPasswordAgain (This just verifies the first password box, doesn't go in db)
txtAbout
tbRating
btnSave
btnCancel
This is my App.Config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFileEntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="PassLock.Properties.Settings.dbMainConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dbMain.mdf;Initial Catalog=dbMain;Integrated Security=True" providerName="System.Data.SqlClient" />
// NOTE: I ADDED INITIAL CATALOG=dbMain.mdf
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb"/>
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Now the code for the application:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.Runtime.InteropServices;
namespace PassLock
{
public partial class frmAddSite : Form
{
string connString = ConfigurationManager.ConnectionStrings["dbMainConnectionString"].ConnectionString;
public frmAddSite()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
txtNickname.Enabled = false;
txtPassword.Enabled = false;
txtUrl.Enabled = false;
txtUsername.Enabled = false;
txtEmail.Enabled = false;
txtAbout.Enabled = false;
tbRating.Enabled = false;
cbShowPassword.Enabled = false;
btnSave.Enabled = false;
btnCancel.Enabled = true;
using (SqlConnection con = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO WebLogins(Nickname, WebsiteURL, WebsiteUsername, WebsitePassword, WebsiteEmail, WebsiteAbout, WebsiteRating) VALUES (@nickname, @websiteURL, @websiteUsername, @websitePassword, @websiteEmail, @websiteRating)", con);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("@nickname", txtNickname.Text);
cmd.Parameters.AddWithValue("@websiteURL", txtURL.Text);
cmd.Parameters.AddWithValue("@websiteUsername", txtUsername.Text);
cmd.Parameters.AddWithValue("@websitePassword", txtPassword.Text);
cmd.Parameters.AddWithValue("@websiteEmail", txtEmail.Text);
cmd.Parameters.AddWithValue("@websiteAbout", txtAbout.Text);
int rating = 0;
if (int.TryParse(tbRating.Text, out rating))
{
cmd.Parameters.Add("@websiteRating", SqlDbType.Int).Value = rating;
}
else
{
cmd.Parameters.Add("@websiteRating", SqlDbType.Int).Value = DBNull.Value;
}
cmd.ExecuteNonQuery();
int iAffectedRecords = cmd.ExecuteNonQuery();
if (iAffectedRecords > 0)
{
MessageBox.Show("successful");
}
else
{
MessageBox.Show("Unsuccessful");
}
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connString);
if (con.State == ConnectionState.Open)
{
con.Close();
this.Close();
}
else
{
this.Close();
}
}
private void frmAddSite_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connString);
con.Open();
}
}
}
Hopefully everything was copied right, the braces should be right, I am not recieving any errors in visual studio so everything looks good. I have the following in my Settings.Settings file:
Name Type Scope Value dbMainConnectionString (ConnectionString) Application Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dbMain.mdf;Initial Catalog=dbMain;Integrated Security=True
I also have a DataSet that is called dbMainDataSet.xsd that has the following properties:
Build Action: None
Copy to: Do not copy
Custom Tool: MSDataSetGenerator
Custom Tool Namespace:
File Name: dbMainDataSet.xsd
Full Path: C:\Users\Andy\Documents\Visual Studio 2015\Projects\PassLock\PassLock\dbMainDataSet.xsd
And my database (dbMain.mdf) has the following properties:
Build Action: None
Copy to: Copy always
Custom Tool:
Custom Tool Namespace:
Full Name: dbMain.mdf
Full Path: C:\Users\Andy\Documents\Visual Studio 2015\Projects\PassLock\PassLock\dbMain.mdf
I don't know if this matters or not but when I go into the Advanced Properties this is what I get:
Advanced:
MultipleActiveResult False
Network Library
Packet Size 8000
Transaction Binding Implicit Unbind
Type System Version Latest
Connection Resiliency
ConnectRetryCount 1
ConnectRetryInterval 10
Context
Application Name .NET SqlClient Data Provider
Workstation ID
Initialization
ApplicationIntent ReadWrite
Asynchronous Process False
Connect Timeout 15
Current Language
Pooling
Enlist True
Load Balance Timeout 0
Max Pool Size 100
Min Pool Size 0
Pooling True
Replication
Replication False
Security
Encrypt False
Integrated Security True
Password
Persist Security Info False
TrustServerCertificate False
User ID
Source
AttachDbFilename C:\Users\Andy\Documents\Visual Studio 2015\Projects\PassLock\PassLock\dbMain.mdf
Context Connection False
Data Source (LocalDB)\MSSQLLocalDB
Failover Partner
Initial Catalog
MultiSubnetFailover False
User Instance False
And under Modify Connection it is:
Data Source: Microsoft SQL Server Database File (SqlClient)
Database File Name (new or existing): Visual Studio 2015\Projects\PassLock\PassLock\dbMain.mdf
Log On to the server: Use Windows Authentication
When I test the connection it is successful
In the packages.config file:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.1.2-beta1" targetFramework="net45" />
</packages>
And last but not least the Program.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PassLock
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
}
}
I am also using a theme on my application, but the textboxes are the normal textboxes that come with visual studio.
I am not sure if you needed all this information but I have seen a bunch of posts where people say they need more information so I gave you it all and hopefully someone can help!
connStringlooks? Are you able to connect with same credentials in SSMS?try/catch/throw/finallyand replace it by putting the connection into ausingblock.