Inserting Data into Local SQL Database through C# Windows Forms Application - c#

I have a Local SQL Database.
My first table is Customers which stores:
customerID (Primary Key, Identity, Auto Incremented),
firstName,
lastName,
address,
email,
postcode,
phoneNumber.
My second table is Groups which stores:
groupID (Primary Key, Identity, Auto Incremented),
groupName.
I have a third table Customer_Groups to link those two tables which stores:
customerID (Foreign Key),
groupID(Foreign Key).
(this third table was used to solve the many to many relationship)
On my New Customer C# Windows Application Form there are Text Boxes to insert a:
first name,
last name,
address,
email,
postcode,
phone number,
group name.
On my submit button click event, how would I insert these values into those three SQL tables above including inserting the ID's into the Customer_Groups table? Any help would be appreciated. Please let me know if I could be more specific.

So i can show u so many help for SQL insert into local table Help
There videos contains so many tricks
U want insert data in all tables at same time. So u have 3 tables then u have to write 3 method for inserting.

Use PetaPoco, available using NuGet. It allows you to set up some simple DTOs, and when you write one into the DB, the DTO is updated with the new id, so you can use that (within a transaction) to write the next item.
It's a pretty simple micro-ORM

Related

Relational SQL Server Databases

I just registered here and this is my very first question. I hope I can explain myself clearly 'cause being a self-taught developer I don't quite speak the jargon.
My question: my project database holds employee information and has things like firstName, lastName, jobTitle, etc.. (static things).
My problem begins when I want to also start collecting all the clockIn & clockOut events of each employee. I can't think of an elegant way of adding these to my current database.
I don't know too much about databases but I think such things should either go in a totally different database or perhaps in a different table within the same database.
No idea which is the right answer.
The other thing is that these 2 databases or 2 tables need to somehow relate to each other somehow. When I select an employee from the list [data coming from the 1st DB or Tbl] and choose to view that specific employee's clock event history [data coming from the 2nd DB or Tbl] I should see that employee's clock in's & out's and NOT some other employee's clock events history.
A step-by-step tutorial is not necessary, but appreciated. Can you give me a quick explanation/outline of how this can be done ? If needed, I can add more details about
the project.
Thanks.
Like so:
CREATE TABLE Employees (
EmployeeId bigint IDENTITY(1,1) PRIMARY KEY,
FirstName nvarchar(50),
LastName nvarchar(50),
etc
)
CREATE TABLE EmployeeClocks ( -- rename as appropriate
EmployeeId bigint, -- foreign key
DateTime datetimeoffset(7),
ClockInType tinyint, -- values defined by an enum inside your program code
CONSTRAINT FK_EmployeeClocks_Employees FOREIGN KEY (EmployeeId) REFERENCES Employees (EmployeeId) ON DELETE CASCADE ON UPDATE CASCADE
)
Now for some queries:
Getting all of the clock-ins for an employee (assuming ClockInType = 1 for clock-ins, and 2 for clock-outs):
SELECT
DateTime
FROM
EmployeeClocks
INNER JOIN Employees ON EmployeeClocks.EmployeeId = Employees.EmployeeId
WHERE
Employees.FirstName = "Dick" AND
Employees.LastName = "Butt"
Read about database schema
You have to use two tables in a single database, Dai's answer showed the tables. just adding a few word if you re new to database then first read about it make a design idea than make database. because it very difficult to change in database when project is done.
Read some articles from here
database architecture
sql server database

How to check if the item has dependencies in the database before updating its status?

I am a new developer of ASP.NET and Linq-To-Entities. I am trying right now to write a general method which will take care of checking if there is any dependency on the item before updating its status. For example, there are many employees under each division. What I want to do that when the user wants to update the status of the division from an Active to Inactive, then this method will tell him that there are active users underneath it. of all users belong to that division will be inactive. This thing is applicable to the other scenarios such us Department, Division and Unit.
I have the following Database structure:
Departments Table: ID, Name, Code, Status, UserId
Divisions Table: ID, Name, Code, Status, UserId, DeptID
Units Table: ID, Name, Code, Status, UserId, DivID
Users Table: ID, Name, Status
Status Table: ID, Status
Could you please tell me how to do that?
Looks like you need to rethink your model if you're expecting multiple users per Dept/Div/Unit, because your current model only has one user for each, which I assume is not what you want. Also it doesn't seem like you want the opposite either (A user belonging to a single Div/Unit/Dept, which would be done by adding DeptId etc to the Users table.)
Instead it looks like you want a many-to-many relationship between Departments and Users, and the correct way to model this is to give those relationships a dedicated table, such as the following:
CREATE TABLE DepartmentUserRel
(
DepartmentId int,
UserId int,
PRIMARY KEY(DepartmentId, UserId)
CONSTRAINT FK_DepartmentUserRel_Department FOREIGN KEY (DepartmentId)
REFERENCES Department (Id)
CONSTRAINT FK_DeparmentUserRel_User FOREIGN KEY (UserId)
REFERENCES Users (Id)
)
Similar tables should exist for each many-to-many relationship between two of your other tables, but they're not necessary for many-to-one/one-to-many relationships.
Once you have the right model, you should really reconsider storing computed values such as Status in the Departments table at all - you should in fact compute them each time you query, and updating the Status should mean updating all users, not just the Status field in the Department.
You should instead use views to create a virtual view of the database structure as you placed it in your question. If we assume the above DepartmentUserRel table has another Status bit, field in it, where TRUE would indicate an active user and FALSE inactive, such that you want to declare a virtual Status field in the Department table which is true if any of the users for that department are active, you create the view something like this:
CREATE VIEW DepartmentView AS
SELECT D.Id as Id, D.Name as Name, Code, SUM(DU.Status) as Status
FROM Departments D, DepartmentUserRel DU
WHERE DU.DepartmentId = D.Id
You query from the DepartmentView much the same way you would query from a regular table, eg SELECT * FROM DepartmentView
Here's the caveat: Views can not be directly inserted or updated, because they may take fields from several tables, but INSERT/UPDATE should only modify one table at a time. We do in fact only want to update one table at a time here - the DepartmentUserRel table. If we want to set Status in DepartmentView to FALSE (inactive), that instead means we want to set Status in the DepartmentUserRel table to FALSE for all relationships of users to that department. We can do this by creating a trigger which catches attempted updates to the view.
CREATE TRIGGER IO_Trigger_Update_Department on DepartmentView
INSTEAD OF UPDATE AS BEGIN
IF ((SELECT Status FROM inserted) = FALSE)
UPDATE DepartmentUserRel SET DU.Status = FALSE
FROM DepartmentUserRel DU, Departments D
WHERE DU.DepartmentId = D.Id
END
(Note that all those code examples are conceptual. I've not tested them and only partially remember the syntax for them, but you should be able to fix them by knowing what to search for.)

Multiple users but storing data in same tables

Hi I am new to databases in general, so forgive my noob question below, but I really do need help.
I have designed a database with 4 tables. I have created an application in C# which will store some values in these 4 tables during the course of the application running. However, this is all working fine when there is only one user of the application, but if more that one user is going to use the same application running in an ASP.NET page, then they will be accessing and altering the data in the 4 tables, and problems will soon arise.
My question is, how do I prevent this from happening? I want each user to have their own unique username and then use that to differentiate them in the tables but my knowledge of databases is limited to know how to achieve this. Please help?
Supposing you have the following table today:
FavoriteFood
—————————————
FoodId
FoodName
And it lists all of your favorite foods. But then you decide you'll let me use your database to store my favorite foods too. Since you don't care about my favorite foods, and I don't care about yours, you need a way of keeping them separate. First, you'll create a User table:
User
—————————
UserId
UserName
FirstName
LastName
Then, you need to relate the User table to the FavoriteFood table. One way of doing this would be to add a Foreign Key to the FavoriteFood table. Give it a new field called UserId:
FavoriteFood
—————————————
FoodId
UserId
FoodName
Then you can get just the food for a single user by adding a WHERE clause to your SQL code:
SELECT FoodName
FROM FavoriteFood
WHERE UserId = #UserId
That could be ok, but I'm not satisfied with it. This database is not normalized! Suppose, you later want to store calorie information about your foods. You add a field called calories to your FavoriteFoods table. As you are populating that field with data, you notice that you are putting in the same data multiple times. All of your users like bananas, so you have as many entries in your table for bananas as you have users. You have to enter the exact same calorie information over and over again. Instead, you should have all the information for a food in the table just once, and use a completely separate table to map food to users:
Food
—————————
FoodId
FoodName
Calories
FavoriteFood
—————————————
FoodId
UserId
Use a join to get the favorite food for a user:
SELECT f.FoodName
,f.Caloires
FROM Food f
JOIN FavoriteFood a ON a.FoodId = f.FoodId
WHERE a.UserId = #UserId

Multiple database records

I want to store emergency help line contacts in database from ASP.NET web site . . .this contacts will be assign to particular locations of different cities. . .
For eg: City=Mumbai and then for Mumbai City there will be various locations like Dadar, Andheri, Borivali , etc .
I have designed a form
now, the problem is that , there can be one airport for multiple locations of a particular city then also i have to enter the entire information for each and every location . . . So is there any way to avoid multiple entries ?
You can use following table schema, and design you form accordingly
Location Table
LocationID (Primary Key)
CountryID (Foreign Key)
CityID (Foreign Key)
ContactID (Foreign Key)
Location
City Table
CityID(Primary Key)
City
Country Table
CountryID(Primary Key)
Country
Service Table
ServiceID(Primary Key)
Service --Airport/Ambulance/fire...
Contact Table
ContactID (Primary Key)
ServiceID (Foreign Key)
Description --AirportName/HospitalName
Contact --Contact Number
UPDATE (Form Design Tips)
Form to add records to City/Country/Service Tables (They are quite simple you just need to check duplicate entry/ Required fields.
For Contact Table use Drop Down for Service that is populated from Service Table
For Location use Drop Downs for Country,City and Contact that are populated from respective tables.
Use INNER JOINS to join the tables and display the desired Results

Making a page where each user has his own information,gridview etc

After the user logged in , I need a page where each registered user has his own gridview and controls binded to his gridview.
The page will contain a sqldatasource binded to the gridview .
I thought about making a new table in the database for each user and in the form load to get the username after the user logged in, get the table name and replace the sqldatasource bind to his table name and the other controls fields for table name to his one.
Or is there any other way of doing this?
You definitely do not want to make a separate table for every user. How on Earth would you plan to scale that to multiple users?
What data does the user need to see on their page? Understand that a gridview doesn't have to map directly to a database table. It can map to any set of data. So you can store the data in your database in a way that makes sense to persist it (relational entities), then query and display it in a way that makes sense to display it.
For example (and it's a contrived example, since we don't know what data you have), if you have users who need to see a list of products that they've ordered, then you wouldn't create a table of products for each user. You'd probably have a table for each of the entities (User, Product, Order, etc.):
Users
----------
ID
Name
etc.
Products
----------
ID
Name
etc.
Orders
----------
ID
UserID
DateOrdered
etc.
And since each order would have a list of products, and each product can be on many orders, that's a many-to-many relationship. So you might create a linking table for that relationship:
OrderedProducts
----------
OrderID
ProductID
Then, for displaying in the UI, you would query the data to get only the products ordered by that user:
SELECT DISTINCT
Products.ID,
Products.Name,
Orders.OrderedDate
FROM
Users
INNER JOIN Orders ON Users.ID = Orders.UserID
INNER JOIN OrderedProducts ON Orders.ID = OrderedProducts.OrderID
INNER JOIN Products ON OrderedProducts.ProductID = Products.ID
WHERE
Users.ID = #userID
This should give you a list of distinct products ordered by that user and when they were ordered. (Note that this code is free-hand, I don't have a database handy to test it.)
So each user would see their own specific information.
You want to make sure that your data is modeled in a usable relational fashion. Define your entities (usually real-world things you're representing in the data) and define tables to represent those entities. Relate them together in natural ways. Relational databases are great at handling complex queries against well-defined data. Don't try to design your database around the nature of the display from the perspective of the user, design it around the nature of the information being stored.
You certainly DO NOT need a separate table for each of your users!
Why don't you just add an additional column to one of your tables to store the username. This way, each record is marked to belong to specific user. Reading the data for logged user is just a matter of simple Where clause on the table.
No thats not right,
You can't create a table for every user. Think if you have 10,000 users than you mean your database contain 10,000 users.
You have to create only one table in which all user's information is saved.
You have to save an identity like user name or email to your database and
When user login to your app by his username or email the information will be taken from table on the basis of username or email and set to gridview.
May it helps you...
this is not Logical to create a table for each user,save all user information in a table is better and faster
for this your can make a table for user information with a user id, and another table for user data entery.and make a relation ship between them

Categories