Default and maximum length of VARCHAR - c#

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

Related

Problem with database connection C# from System.Data.SqlClient

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.

Error : String or binary data would be truncated. The data for table-valued parameter doesn't conform to the table type of the parameter

I am getting error
String or binary data would be truncated. The data for table-valued parameter doesn't conform to the table type of the parameter.The statement has been terminated.
Stored procedure is:
CreatePROCEDURE [dbo].[addquestion]
#dt as MyDataTable readonly
AS
BEGIN
insert into questiontbl(Question)
select(Question)
from #dt;
END
The table is:
CREATE TABLE [dbo].[questiontbl]
(
[checkval] [varchar](max) NULL,
[Question] [varchar](max) NULL
)
C# code:
con.Close();
con.Open();
DataTable sqa = Session["questionlist"] as DataTable;
SqlParameter tvparam = cmd.Parameters.AddWithValue("#dt", sqa);
tvparam.SqlDbType = SqlDbType.Structured;
cmd.ExecuteNonQuery();
Cmd.ExecuteNonQuery() returns the error mentioned. I have matched the datatype - it is varchar(max) in type and table as well.
I have referred many url but didn't get proper solution for this.
The main reason for this issue is, we are not passing the data in the
specified length
But in our actual code we will be sent the valid data, but the value will not be passed and will through the mentioned issue.
Here the trick is,
While creating data table for the table valued parameter, we need to
create the column in the order we created in the table valued
parameter.
Please check the following code.
Solution (The following will work)
C#
DataTable users= new DataTable("Users");
users.Columns.Add("EmailAddress", typeof(string));
users.Columns.Add("Content", typeof(string));
DataTable data= users.NewRow();
data["EmailAddress"] = emailAddress;
data["Content"] = content;
Sql
CREATE TYPE [dbo].[ParamEulaEmailUser] AS TABLE(
[EmailAddress] [nvarchar](50) NOT NULL,
[Content] [nvarchar](max) NULL
)
The following will not work
c#
DataTable users= new DataTable("Users");
users.Columns.Add("Content", typeof(string));
users.Columns.Add("EmailAddress", typeof(string));
The reason is here while we sending data to the stored procedure, the table valued parameter takes the value in the given order and match with existing column in the order. So the content will be checked with the email address in the stored procedure and throw the following error
Error : String or binary data would be truncated. The data for table-valued parameter doesn't conform to the table type of the parameter
You have not posted the declaration for MyDataTable user-defined type, but you should increase the varchar size of the Question column in the MyDataTable definition.
DROP TYPE [dbo].[MyDataTable]
GO
CREATE TYPE [dbo].[MyDataTable] AS TABLE
(
[Question] [varchar](200) NULL --INCREASE THIS VALUE
)
Script a Drop and Create for the addquestion procedure, as well as the MyDataTable type.
Drop the stored proc, drop the MyDataTable type.
Edit the MyDataTable Create script as I mentioned, and run it, then create part for the stored proc.
The maximal length of the target column is shorter than the value you try to insert.
Rightclick the table in SQL manager and go to 'Design' to visualize your table structure and column definitions. increase column Length

SQL table doesn't exist

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.

MySqlBackup.NET QueryExpress.ExecuteScalarStr() outputs strings enclosed in double-quotes instead of backticks

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();
}
}
}

Filling a DataSet which contains a DateTime column with Sqlite Databases

I am working on a C# WPF project which uses an SQLite database. I am trying retrieving the data from a table within the sqlite database and add to a data set so I can add the data set to the items source of the data grid. One of the columns is a DateTime column but I am getting the following error:
String was not recognized as a valid DateTime.
Below is how I am retrieving the data
private DataSet getAlarmsForSqlite()
{
DataSet ds = new DataSet();
try
{
using (ConnectSQLiteDatabase db = new ConnectSQLiteDatabase(dbPassword))
{
string query = "SELECT * FROM alarms ORDER BY date";
SQLiteDataAdapter da = new SQLiteDataAdapter(query, db.conn);
da.Fill(ds);
}
}
catch (SQLiteException ex)
{
Console.WriteLine("Failed to get alarms. Sqlite Error: {0}", ex.Message);
return null;
}
return ds;
}
And below is the create statement for the table
CREATE TABLE `alarms` (`id` int(11) NOT NULL, `date` datetime NOT NULL,
`type` varchar(50) NOT NULL,
`message` mediumtext NOT NULL,
`level` varchar(45) NOT NULL,
`page` varchar(500) NOT NULL,
`acknowledged` char(1) DEFAULT '0', PRIMARY KEY (`id`))
Thanks for any help you can provide.
try this way
select * from alarms order by date(date) DESC
see the documentation.
There's some discussion regarding this issue here; sqlite throwing a "String not recognized as a valid datetime"
Apparently the SQLite datetime to C# DateTime serialization mapping doesn't exactly work. To me, it sounds like the datetime is coming back as a string so you need to do DateTime.Parse() in your code. In one of the answers to that question it suggests the datetime also needs to be cast to an nvarchar in order for it work.
It is one of two things:
The data in your table is actually in a format which SQLite is not
capable of turning into a datetime. For best results use the
ISO8601 date format "yyyy-MM-dd HH:mm:ss.FFFFFFF". It requires
conversion before writing the data to the database, but is
transparently handled when reading the data back to the dataset.
The ORDER BY term in your query is for some reason preventing the
SQLiteDataAdapter from identifying the correct type for the
column. Even if you order by some other column, the result will be
the same. To avoid the problem, remove the ordering term (which will
then identify the column data type correctly) and sort your DataSet
after it has been filled.
EDIT: After looking into the recommendation of Ramesh, when using the "date" function with the Order By, the behavior outlined in my second point no longer happened.

Categories