I have a problem with ADO.NET query. I Create Database successfuly. There is only one table (RegUsers) in this database (I am just testing the work with ADO.NET). EDIT: Databese is based on Microsoft Azure
Create of a my table:
CREATE TABLE [dbo].[RegUsers] (
[Id] INT NOT NULL,
[Login] VARCHAR (50) NOT NULL,
[Password] VARCHAR (50) NOT NULL,
[Name] VARCHAR (50) NOT NULL,
[Surname] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC));
I create SqlConnecion and successfully connect to the database (I hope that successfully if I can Open the connection) and then I'd like to INSERT data into this table with this:
SqlConnectionStringBuilder csBuilder;
csBuilder = new SqlConnectionStringBuilder();
csBuilder.DataSource = "********.database.windows.net";
csBuilder.Encrypt = true;
csBuilder.TrustServerCertificate = false;
csBuilder.UserID = "************".ToString();
csBuilder.Password = "********".ToString();
csBuilder.ConnectTimeout = 30
SqlConnection con = new SqlConnection(csBuilder.ToString());
con.Open();
string PlneniDaty =
#"INSERT INTO [dbo].[RegUsers] (Login,Password,Name,Surname)"+
#" VALUES ('MyLogin','MyPassword','Pavel','Novak')";
SqlCommand NaplDaty = new SqlCommand(PlneniDaty, con);
NaplDaty.ExecuteNonQuery();
con.Close();
Whenever I execute this command It display Error:
Invalid object name 'dbo.RegUsers'
(and yes the table was successfully created I can see it in SQL Server object Explorer)
Where is the problem?
Your entire code looks good.you can post your connectionString.
Following things you need to check.
Connection String ( Data Source Name , Database Name )
Schema of your table.
If I understand correctly, you're executing a insert query in a database dbo.RegUsers and it's giving the error Invalid object name 'dbo.RegUsers'? That simply means that table cannot find an object called "RegUsers ". There are several possible reasons for this:
The object doesn't exist, possibly because the schema and/or database don't exist
The object exists, but the database is case-sensitive and some part of the name doesn't match the name in your code
You'll need to investigate more to find out what the cause is in your case, but as a complete guess, your production server has both the RegUsers and databases?
Finally, when posting questions please always include your SQL Server version (2000/2005/2008) and edition (Express, Standard, Enterprise); they can be very important when talking about schemas and permissions, because features and behaviour can be different.
As far as I can see from your create script, your table's name is RegUzivatele, while you're trying to insert to a table name RegUsers, which of course doesn't exist.
Related
I have looked at all the similar questions on this topic but none seem to work for me.
When I try to run my application, I get the following error:
System.Data.SqlClient.SqlException: 'Cannot insert the value NULL into column 'Id', table 'C:\FINALLY\DATABASE.MDF.dbo.loginTB'; column does not allow nulls. INSERT fails.
Here is my code:
private void btnContinued_reg_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\finally\DataBase.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd= new SqlCommand("insert into loginTB(username,password)values('" + txtUserName_reg.Text + "','" + txtPaswword_reg.Text + "')",cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("good");
}
What am I doing wrong?
A snapshot of my code:
The problem does not indicate a connection problem at all. It seems that you are trying to insert a record into a table, and you are trying to pass null as the id, which gives you the error.
My guess would be the error is in the definition of that table loginTB, you make sure the column id has the property IDENTITY, since you are using SQL Server.
An example would be like this:
CREATE TABLE new_employees
(
id_num int PRIMARY KEY IDENTITY(1,1),
fname varchar (20),
minit char(1),
lname varchar(30)
);
Identity columns can be used for generating key values. The identity property on a column guarantees the following:
Each new value is generated based on the current seed & increment.
Each new value for a particular transaction is different from other concurrent transactions on the table.
The identity property on a column does not guarantee the following:
Uniqueness of the value
Uniqueness must be enforced by using a PRIMARY KEY or UNIQUE constraint or UNIQUE index.
Follow up answer of previous answers.
If you already created a table and want to modify it to work correctly:
Go to the table properties from SSMS tool and select the identity column and save the properties. Identity column must be marked as not nullable.
I am very new to Apache Phoenix. I have created table using query in SQuirrel SQL client. Here I shared the sample query below.
CREATE TABLE IF NOT EXISTS Sample(Action VARCHAR NOT NULL, Title VARCHAR, Email VARCHAR, Type VARCHAR CONSTRAINT PKforum PRIMARY KEY (Action));
Title column has the value which maximum size is 200 characters.
Then I tried to fetch data from Apache Phoenix using Simba Pheonix ODBC driver. For this, used the below C# code..
OdbcConnection connection = new OdbcConnection("Driver={Simba Phoenix ODBC Driver};host=<host name>;port=8765");
connection.Open();
OdbcCommand command = new OdbcCommand(query,connection);
OdbcDataReader dataReader = command.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(dataReader);
connection.Close();
When loading data table I got the below exception.
failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
If I change my query like below its working fine.
CREATE TABLE IF NOT EXISTS Sample(Action VARCHAR NOT NULL, Title VARCHAR(300), Email VARCHAR, Type VARCHAR CONSTRAINT PKforum PRIMARY KEY (Action));
Here my doubt is,
What is the default size and maximum size of VARCHAR in Phoenix server?
Range will be the type of int as mentioned below ..
https://phoenix.apache.org/language/index.html#int
I'm using MySqlBackup.dll (MySqlBackup.NET) which in turn uses MySql.Data.dll to dump the database. I thought MySqlBackup.NET was causing this behavior, so I took it out of the equation. If I run this code in my solution:
Dim cmd = New MySqlCommand()
cmd.Connection = New MySqlConnection(connectionString)
cmd.Connection.Open()
Dim result = QueryExpress.ExecuteScalarStr(cmd, "SHOW CREATE TABLE `airportcodes`;", 1)
cmd.Connection.Close()
I get
CREATE TABLE "airportcodes" (
"AirportCodeId" int(11) NOT NULL AUTO_INCREMENT,
"Code" varchar(4) CHARACTER SET utf8 NOT NULL,
"AirportName" varchar(100) CHARACTER SET utf8 DEFAULT NULL,
"Website" varchar(100) CHARACTER SET utf8 DEFAULT NULL,
"LastUpdate" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY ("AirportCodeId")
)
which I cannot use to restore because it uses double quotes. This happens when I use both the code above and MySqlBackup.NET. If I use the MySqlBackup.NET test application provided with its source code, the result is correct (uses backticks instead of double-quotes).
If I execute this query in the mysql CLI I also get the correct version (with backticks). I am using the same connection string all over.
It feels stupid to search-and-replace after the dump is created. What could be the cause of this?
This has nothing to do with MySqlBackup.NET
It is the behavior of MySql Server which can be configured either as default (GLOBAL) behavior or temporary (SESSION) behavior of MySQL server.
Here is the SQL statements that you can try out yourself:
Example 1: Export table structure with double quotes:
set session sql_mode=ANSI_QUOTES;
show create table `configkey`;
output:
CREATE TABLE "configkey" (
"key" varchar(100) NOT NULL,
"value" text,
PRIMARY KEY ("key")
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Example 2: Export table structure with single quote
set session sql_mode=traditional;
show create table `configkey`;
output:
CREATE TABLE `configkey` (
`key` varchar(100) NOT NULL,
`value` text,
PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
For more information, please refer to official MySQL documentation under the topic: SQL-MODE
https://dev.mysql.com/doc/refman/5.7/en/server-options.html#option_mysqld_sql-mode
https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html
If you see the column names are wrapped with double quotes by default, it's most probably your MySQL server is configured to react in that way by default. You may consult your MySQL server administrator or provider.
Alternatively, you can configure the SQL_MODE each time manually before executing MySqlBackup.NET. Below is an example:
using (MySqlConnection conn = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand())
{
using (MySqlBackup mb = new MySqlBackup(cmd))
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "set session sql_mode=traditional;";
cmd.ExecuteNonQuery();
mb.ExportToFile(file);
conn.Close();
}
}
}
Apologies for this being so long, but I have seen so many questions that include too little info... If someone sees my error(s) in the first few lines, I will be delighted...
I have an SQL Server 2008 R2 database, and can't get what I believe should be the correct behaviour when connecting through a C# SqlConnection.
I have two C# applications built with Visual C# 2010 Express:
One for data import/export/reporting and browsing
One for doing some complex processing
This is all on Windows 7 with all updates etc...
Some of the tables used by each of these two applications are shared common tables, and others need to be kept separated. Since I need to be able to transform and transfer data between the two sides, I want to keep all of this in one database.
To keep some degree of separation, I have created two schemas, two users, two roles and two logins, like:
CREATE LOGIN [Import_User] WITH PASSWORD=N'*****'
CREATE LOGIN [Engine_User] WITH PASSWORD=N'*****'
CREATE USER [Import_User] FOR LOGIN [Import_User] WITH DEFAULT_SCHEMA=[Import_Schema]
CREATE USER [Engine_User] FOR LOGIN [Engine_User] WITH DEFAULT_SCHEMA=[Engine_Schema]
CREATE ROLE [Import_Role] AUTHORIZATION [dbo]
CREATE ROLE [Engine_Role] AUTHORIZATION [dbo]
EXEC('CREATE SCHEMA [Import_Schema] AUTHORIZATION [Import_User]')
EXEC('CREATE SCHEMA [Engine_Schema] AUTHORIZATION [Engine_User]')
-- Import role permissions on the Import schema
GRANT EXECUTE, DELETE, INSERT, SELECT, UPDATE, REFERENCES ON SCHEMA::[Import_Schema] TO [Import_Role]
-- Engine_Role permissions on the engine schema
GRANT EXECUTE, DELETE, INSERT, SELECT, UPDATE, REFERENCES ON SCHEMA::[Engine_Schema] TO [Engine_Role]
EXEC sp_addrolemember N'Import_Role', N'Import_User'
EXEC sp_addrolemember N'Engine_Role', N'Engine_User'
GRANT CONNECT TO [Import_User]
GRANT CONNECT TO [Engine_User]
Then I create some tables and stored procs in each of the schemas, appropriate to each role. There are maybe 20 tables in the engine schema, 30 or so in the import schema. Some of these are very similar in the two schemas, but not quite the same, like:
CREATE TABLE [Engine_Schema].[Problem](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[Description] [varchar](max) NULL,
CONSTRAINT [PK_Status] PRIMARY KEY CLUSTERED ( [ID] ASC )
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCK = ON) ON [PRIMARY])
ON [PRIMARY]
CREATE TABLE [Import_Schema].[Problem](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[Client] [varchar](50) NOT NULL,
[Description] [varchar](max) NULL,
CONSTRAINT [PK_Status] PRIMARY KEY CLUSTERED ( [ID] ASC )
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCK = ON) ON [PRIMARY])
ON [PRIMARY]
This all seems to work fine when I check using those two logins through SSMS - each login sees exactly the tables and SPs that I expect. In each case, I can run queries and USPs inside SSMS without needing to use the schema prefix because these connections use the default schema that I have set up for each login / user. If I login as 'sa', then of course I can see everything in both schemas.
In my C# code, I connect to the database like this:
SqlConnection dbConnection = new SqlConnection(""server=laptop; database=test; user id=Engine_User; password=*****; Trusted_Connection=yes; connection timeout=30");
dbConnection.Open();
then I try to query the database tables directly like this:
using (SqlCommand cmdSelectProblems = new SqlCommand()) {
cmdSelectProblems.Connection = dbConnection;
cmdSelectProblems.CommandText = "Select ID, Name from Problem order by Name";
DataTable dataTableProblems = new DataTable();
using (SqlDataAdapter dataAdapterProblems = new SqlDataAdapter(cmdSelectProblems)) {
dataAdapterProblems.Fill(dataTableProblems);
...
or I can try to use one of my stored procedures like this:
using (SqlCommand cmd = new SqlCommand()) {
cmd.Connection = dbConnection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SelectProblems";
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(_problemsTable);
}
But when I try to use the connection through my C# code like these examples, I get errors like:
Invalid object name 'Problem'
or
Could not find stored procedure 'SelectProblems'
I seem to need to use the explicit schema prefix to get access to those same DB objects in the database. With the schema prefix explicitly included things all work from my C# code as far as I have tested them, so change the direct table query to:
cmdSelectProblems.CommandText = "Select ID, Name from [Engine_Schema].Problem order by Name";
or try to access the USPs with the schema prefix like:
cmd.CommandText = "[Engine_Schema].SelectProblems";
and then everything works fine.
Now I know that using explicit schema names is best practice, but I have a whole shedload of code both in C# and as stored procs that is written without using those schema prefixes. It will be really much simpler if I can make the C# SqlConnection queries respect the default schemas for the logins that I have defined and use. I believe that this should work fine the way I have set it up, but I guess I must have missed something somewhere.
I have wasted two days on this so far, and all that I have read suggests that this should all just work.
server=laptop; database=test; user id=Engine_User; password=*;
Trusted_Connection=yes; connection timeout=30
There's your problem - you're using Windows authentication instead of SQL authentication. Change you connection string to Trusted_Connection=no and everything should work.
Set the users default schema on the rmdbs
USE AdventureWorks;
ALTER USER Engine_User WITH DEFAULT_SCHEMA = Engine_Schema;
GO
Do the same for Import schema
I am really struggling to insert some data into 2 database tables.
I am using Linq over WCF Data Services using Entity Framework 4.
The 2 tables look like this:
CREATE TABLE [dbo].[Accounts] (
[Id] int IDENTITY(1,1) NOT NULL,
[Email] nvarchar(max) NOT NULL,
[Password] nvarchar(max) NOT NULL
);
CREATE TABLE [dbo].[Employees] (
[Id] int IDENTITY(1,1) NOT NULL,
[Name] nvarchar(max) NOT NULL,
[Role] nvarchar(max) NOT NULL,
[Account_Id] int NOT NULL
);
ALTER TABLE [dbo].[Employees]
ADD CONSTRAINT [FK_EmployeeAccount]
FOREIGN KEY ([Account_Id])
REFERENCES [dbo].[Accounts]
([Id])
ON DELETE NO ACTION ON UPDATE NO ACTION;
Each Employee must have just 1 Account. However, an Account may not have any Employees at all.
I have generated the entities, and exposed a DataService which is setup with relaxed access rules:
config.SetEntitySetAccessRule( "Accounts" , EntitySetRights.All );
config.SetEntitySetAccessRule( "Employees" , EntitySetRights.All );
Using LinqPad I can successfully insert an single Account row like this:
var context = this;
Account account = Account.CreateAccount(1, "foo#example.com", "p#ssword");
context.AddToAccounts(account);
context.SaveChanges();
I can see from SQL Server that the row has been inserted, and LinqPad reports no error.
The problem is when I try to insert both a related Account and Employee row together.
I am sure the code below should work?
var context = this;
Account account = Account.CreateAccount(1, "foo#example.com", "password");
context.AddToAccounts(account);
Employee employee = Employee.CreateEmployee(1, "Foo", "Developer");
employee.Account = account;
context.AddToEmployees(employee);
context.SaveChanges();
The response I get back from the server (with verbose errors enabled) basically says that:
Account row inserted successfully (HTTP 201)
Employee row did not insert (HTTP 500)
The full error is:
Entities in 'DbContainer.Employees' participate in the 'EmployeeAccount' relationship. 0 related 'Account' were found. 1 'Account' is expected.
Does anybody have an example that works against WCF Data Services?
For anybody reading this the solution was to add the following line before SaveChanges()
context.SetLink(employee, "Account", account);
Simply assigning the account to the employee was not enough, a Link also needed to be established.