Connecting to Google Cloud SQL in C# - c#

I currently have a Google Cloud SQL instance with some tables that I've created using the following format:
-- Create Hotel table with hotelNo primary key
CREATE TABLE IF NOT EXISTS Hotel(
hotelNo INT NOT NULL AUTO_INCREMENT,
hotelName VARCHAR(255) NOT NULL,
city VARCHAR(255) NOT NULL,
PRIMARY KEY(hotelNo)
);
-- Create Room table with roomNo and hotelNo for the composite key (primary)
CREATE TABLE IF NOT EXISTS Room(
roomNo INT NOT NULL AUTO_INCREMENT,
hotelNo INT NOT NULL,
roomType VARCHAR(255) NOT NULL,
price INT NOT NULL,
PRIMARY KEY(roomNo, hotelNo)
);
-- Create Booking table with hotelNo, guestNo and dateFrom for the composite key (primary)
CREATE TABLE IF NOT EXISTS Booking(
hotelNo INT NOT NULL,
guestNo INT NOT NULL,
dateFrom DATE NOT NULL,
dateTo DATE NOT NULL,
roomNo INT NOT NULL,
PRIMARY KEY(hotelNo, guestNo, dateFrom)
);
-- Create Guest table with guestNo primary key
CREATE TABLE IF NOT EXISTS Guest(
guestNo INT NOT NULL AUTO_INCREMENT,
guestName VARCHAR(255) NOT NULL,
guestAddress VARCHAR(255) NOT NULL,
PRIMARY KEY(guestNo)
);
I am building a small application for class that will allow me to connect to my database on the cloud and then perform basic queries against it. My tables are already loaded with some data so that I am able to carry out basic CRUD operations.
I was wondering how, using C# and from my local machine I could connect to this instance. I have activated the Google SQL API and have downloaded the Google NuGet package but am still having some difficulty figuring out the rest.
I have read some of Google's documentation on this but am hoping to find a more straightforward and simple answer from the community.
Any ideas on how I should move forward? At least for now, I'd like to just be able to simply connect and possibly do a SELECT * FROM Hotel query and see the results on the command prompt.

Related

Azure hosted Database having a single column cleared at random

We have written a c# MVC ASP.NET CORE project which is hosted as an azure app-service and is driven by an azure hosted sql server.
I have the following sql Table as a part of the database:
CREATE TABLE [dbo].[Users] (
[UserID] INT IDENTITY (1, 1) NOT NULL,
[UserName] NVARCHAR (50) NOT NULL,
[Email] NVARCHAR (50) NOT NULL,
[Active] BIT DEFAULT ((1)) NOT NULL,
[TeamID] INT NULL,
[UserType] INT DEFAULT ((0)) NOT NULL,
[UserCpM] FLOAT (53) DEFAULT ((0)) NOT NULL,
[CpMSet] BIT DEFAULT ((0)) NOT NULL,
[CurrentProject] INT DEFAULT ((-2)) NOT NULL,
[CurrentNotes] NVARCHAR (MAX) NULL,
[TimeStarted] DATETIME NOT NULL,
[Failure] BIT DEFAULT ((0)) NOT NULL,
[Failure_Project] INT NULL,
[Failure_TimeStarted] DATETIME NULL,
[Failure_TimeEnded] DATETIME NULL,
[Failure_Notes] NVARCHAR (MAX) NULL,
PRIMARY KEY CLUSTERED ([UserID] ASC),
CONSTRAINT [FK_Users_ToTeams] FOREIGN KEY ([TeamID]) REFERENCES [dbo].[Teams] ([TeamID]),
CONSTRAINT [FK_Users_CurrentProject_ToProjects] FOREIGN KEY ([CurrentProject]) REFERENCES [dbo].[Projects] ([ProjectID]),
CONSTRAINT [FK_Users_FailureProject_ToProjects] FOREIGN KEY ([Failure_Project]) REFERENCES [dbo].[Projects] ([ProjectID])
);
The UserCpM field is an indication of employees cost-per-minute and as such is cleared before displaying to any user who is not of the highest privilege level. Over the last couple of days this field has been randomly resetting itself back to 0 for every entry in the table in the database.
I have hunted through the code and confirmed that on any view where the CpM is cleared it is re-set before saving the User back to the database so I'm fairly certain that that isn't the cause of the issue.
Is there any reason that the context would save it's changes without being told to do so? or alternatively is it possible that it will track changes to anything set from it and transfer them back to the database.
Is there any reason that the context would save it's changes without being told to do so?
No, Azure SQL or SQL Server hosted on Azure will not modify your data.
is it possible that it will track changes to anything set from it and transfer them back to the database.
I suggest you create a log table and 2 triggers for your Users table. If any updates has been applies on Users table. It triggers will write the operation time and the UserCpM changes to the log table.
Here is a insert trigger code sample.
CREATE TRIGGER dbo.UsersInsert
ON [dbo].[Users]
AFTER Insert
AS
BEGIN
insert into dbo.UserLog(UserID, OriginalUserCpM, NewUserCpm, ModifiedDate)
select UserID, null, UserCpm, GETDATE() from inserted
SET NOCOUNT ON;
END
Here is a update trigger code sample.
CREATE TRIGGER dbo.UsersUpdate
ON [dbo].[Users]
AFTER Update
AS
BEGIN
insert into dbo.UserLog(UserID, OriginalUserCpM, NewUserCpm, ModifiedDate)
select UserID, UserCpm, null, GETDATE() from deleted
insert into dbo.UserLog(UserID, OriginalUserCpM, NewUserCpm, ModifiedDate)
select UserID, null, UserCpm, GETDATE() from inserted
SET NOCOUNT ON;
END

how to manage Student and Book issuing relation in Library Management System in C# .net?

In Library Management System, how to keep transaction done by student in taking book....I have got two table Student and Book which have one to many relationship...Now if any student is issuing 5 different book then how this information is stored in Database?? please help
A Student can borrow zero or more Books, a Book is borrowed by zero or more Students. This is a textbook many to many relationship and it requires a third table
So you need a Borrows table with a structure like this
Create Table Borrows
(
IDBook int not null,
IDStudent int not null,
BorrowDate smalldatetime not null,
ReturnDate smalldatetime null,
BookStatusBefore nvarchar(32) not null,
BookStatusAfter nvarchar(32) not null
)
-- Primary key on IDBook+IDStudent....
ALTER TABLE Borrows ADD CONSTRAINT PK_Borrows PRIMARY KEY CLUSTERED
(
IDBook,
IDStudent
)
Now you can register a Borrow event and keep track of the whereabout of a book and other historical information about the event itself.

sql tables to xml

I have got few tables in sql database, one of that contains names of others, but not all. I need to load names of tables (from that special one) as a list (xdocument), and using foreach and a simple query convert all of that to one xml file. database and app is on same azure account.
i have few table like that
CREATE TABLE [dbo].[table_name]
(
[P_ID] INT NOT NULL,
[name] NVARCHAR (255) NOT NULL,
PRIMARY KEY CLUSTERED ([P_ID] ASC)
);
and one with only varchar that contains
table_name1
table_name2
table_name4
i use that simple query
SELECT
P_ID "Table_name2/#id",
nazwa "Table_name2"
FROM Table_name2
FOR XML PATH('');
and get result, but only for one table
something
but i want a result for few tables in one xml using "file_converting_tables_to_xml.cs" in my app
<spinery>
<spiner title="Table_name1">
<wart id="1">black</wart>
</spiner>
<spiner title="Table_name3">
<wart id="1">white</wart>
</spiner>
or something similar
all that i found about it don't work for me,
so please help
If this was SQL Server you might try this:
--Creating two tables
CREATE TABLE [dbo].Table_name1
(
[P_ID] INT NOT NULL,
[name] NVARCHAR (255) NOT NULL,
PRIMARY KEY CLUSTERED ([P_ID] ASC)
);
CREATE TABLE [dbo].Table_name2
(
[P_ID] INT NOT NULL,
[name] NVARCHAR (255) NOT NULL,
PRIMARY KEY CLUSTERED ([P_ID] ASC)
);
GO
--Fill them with your sample data
INSERT INTO dbo.Table_name1 VALUES(1,'black');
INSERT INTO dbo.Table_name2 VALUES(1,'white');
GO
--Use UNION ALL to combine the results and FOR XML PATH to create the proper namings
SELECT 'Table_name1' AS [#title]
,P_ID [wart/#id]
,name [wart]
FROM Table_name1
UNION ALL
SELECT 'Table_name2' AS [#title]
,P_ID [wart/#id]
,name [wart]
FROM Table_name2
FOR XML PATH('spiner'),ROOT('spinery');
--Clean-Up (Carefull if real data!)
GO
--DROP TABLE dbo.Table_name1;
--DROP TABLE dbo.Table_name2;

How to add sequential numbering to SQL tables from C# [closed]

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 want to have my tables all contain a unique number for my tableID column.
Insert sequential number in MySQL
This is pretty much what I'm trying to accomplish but from my C# app.
EDIT: Adding the ID column with Primary Key and Auto Increment was all I needed to do. Thank you deterministicFail
From your error log:
ERROR 1067: Invalid default value for 'Status'
SQL Statement:
ALTER TABLE `lianowar_woodlandlumberbook`.`book`
CHANGE COLUMN `Customer_Ph` `Customer_Ph` VARCHAR(16) NOT NULL ,
CHANGE COLUMN `Status` `Status` VARCHAR(10) NOT NULL DEFAULT NULL ,
DROP PRIMARY KEY,
ADD PRIMARY KEY (`Customer_Name`, `Status`)
ERROR: Error when running failback script. Details follow.
ERROR 1050: Table 'book' already exists
SQL Statement:
CREATE TABLE `book` (
`Customer_Name` varchar(20) NOT NULL,
`Customer_Ph` varchar(16) DEFAULT NULL,
`Customer_Ph2` varchar(30) NOT NULL,
`Info_Taken_By` varchar(12) NOT NULL,
`Project_Type` varchar(20) NOT NULL,
`Project_Size` varchar(20) NOT NULL,
`Date_Taken` varchar(5) NOT NULL,
`Date_Needed` varchar(5) NOT NULL,
`Sales_Order` varchar(5) NOT NULL,
`Information` text NOT NULL,
`Status` varchar(10) DEFAULT NULL,
`tableID` varchar(5) DEFAULT NULL,
PRIMARY KEY (`Customer_Name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
You try to define a NOT NULL column and give it the default NULL. You should consider your datatypes, tableID should be a number datatype (btw the name isn't good, just id or bookId would be better).
To your question:
You should define the table like this
CREATE TABLE `book` (
`ID` INT NOT NULL AUTO_INCREMENT,
`Customer_Name` varchar(20) NOT NULL,
`Customer_Ph` varchar(16) DEFAULT NULL,
`Customer_Ph2` varchar(30) NOT NULL,
`Info_Taken_By` varchar(12) NOT NULL,
`Project_Type` varchar(20) NOT NULL,
`Project_Size` varchar(20) NOT NULL,
`Date_Taken` varchar(5) NOT NULL,
`Date_Needed` varchar(5) NOT NULL,
`Sales_Order` varchar(5) NOT NULL,
`Information` text NOT NULL,
`Status` varchar(10) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
I dont know which datatypes you really need, because i dont know the data you going to store. But to use the Primary Key and Auto_increment feature this will do the trick.
Don't do this from application code. Ever. Application code is poorly positioned to guarantee uniqueness, because you have a potential race condition between multiple clients trying to insert at about the same time. It will also be slower, because application code must first request a current value from the database before incrementing it, resulting in two separate database transactions.
The database, on the other hand, already has features to ensure atomicity and uniqueness, and can respond to requests in order, thus positioning it to do this job much faster and better. Indeed, pretty much every database out there, including MySql, already has this feature built in.

Unexplainable MySQL composite key issue with .NET Application

I am writing a .NET application that interact with MySQL database using ODBC connection. My application will create the database schema and tables on the database upon start up. However, I encountered a weird unexplainable case below:
First my application will create the following table
CREATE TABLE IF NOT EXISTS `sample` (
`item_ID` varchar(20) NOT NULL,
`item_No` int(11) NOT NULL,
`sample_col1` varchar(20) NOT NULL,
`sample_col2` varchar(20) NOT NULL,
PRIMARY KEY (`item_ID`, `item_No`)
) ENGINE=InnoDB;
Populate the table with
INSERT INTO sample SET item_ID='abc', item_No=1, sample_col1='', sample_col2='';
INSERT INTO sample SET item_ID='abc', item_No=2, sample_col1='', sample_col2='';
Then I execute a SELECT query from within the .NET application using the following code:
Dim query As String
query = "SELECT item_ID, item_No, sample_col1, sample_col2 FROM sample"
Dim conn As New OdbcConnection("Driver={MySQL ODBC 5.1 Driver};Server=localhost; port=3306;Database=test; User=dbuser;Password=dbpassword;Option=3;")
Dim cmd As New OdbcDataAdapter(query, conn)
Dim dt As New DataTable
cmd.FillSchema(dt, SchemaType.Source)
cmd.Fill(dt)
conn.Close()
The cmd.Fill(dt) line will throw an Exception: "Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints".
However if I modify the table creation query to:
CREATE TABLE IF NOT EXISTS `sample` (
`item_ID` varchar(20) NOT NULL,
`item_No` int(11) NOT NULL,
`sample_col1` varchar(20) NOT NULL,
`sample_col2` varchar(20) NOT NULL,
PRIMARY KEY (`item_No`,`item_ID`) '--> Here Primary Key order is inverted
) ENGINE=InnoDB;
The vb.net code works perfectly. Notice on the second creation query I inverted the order of the PRIMARY KEY creation. On the first example I put item_ID first while on the second example I put item_No first.
Does anyone has any clue why this is happening? Also is there any difference from the point of view of MySQL database between the first and second create query?
Any input will be appreciated. Thank you !

Categories

Resources